you-dont-need / You-Dont-Need-Lodash-Underscore

List of JavaScript methods which you can use natively + ESLint Plugin
MIT License
18.74k stars 815 forks source link

No example for _.set #395

Open a-roberts opened 7 months ago

a-roberts commented 7 months ago

Hi, I run a Code Transformation Guild on the side where I work and, frankly, I love the readme for this repository - it's fantastic. I'm intending to use this as repo as an example as we move developers off Lodash in favour of some of the suggestions here.

Only one problem...we can't see a ._set example.

Is this because it's super easy to do, or so general it'd be a pain to do effectively?

I figured I'd be able to see an existing issue for this but...I don't.

Cheers

binury commented 7 months ago

Yeah if you look at what set is doing, you'll see it is a bit heavy handed 😥 With all the "safety checks" and flexibility and edge cases, it's probably ~150 LoC across half a dozen files.

A mvp bare set, as a partner to get (basically), would be something like… `

/**
 * @param {Object} obj
 * We'll make assumptions about path in order to avoid reimplementing
 * https://github.com/lodash/lodash/blob/main/src/.internal/stringToPath.ts
 * @param {Array|string} path
 * @param {*} value
 * @returns {Object} Returns obj
 */
function set(obj, path, value) {
  path = Array.isArray(path) ? path.join('.') : path;
  const paths = path
    .split('.')
    .map((p) => (isNaN(parseInt(p, 10)) ? p : parseInt(p, 10)));
  const lastIndex = paths.length - 1;

  let nested = obj;
  for (const [i, p] of paths.entries()) {
    if (i === lastIndex) {
      nested[p] = value;
    } else {
      nested =
        nested[p] || (nested[p] = typeof paths[i + 1] === 'number' ? [] : {});
    }
  }
  return obj;
}
const person = {
  birth: {
    dateTime: '',
    location: {
      state: 'CA',
      city: 'Los Angeles',
      hospital: {
        name: '',
      },
    },
  },
};

set(person, ['birth', 'location', 'hospital', 'name'], 'Hollywood Pediatrics');
set(person, 'vehicle.manufacturer', 'Toyota');
set(person, 'parents.0.name', 'John Doe');

console.log(person);
/*

{
  birth: {
    dateTime: '',
    location: { state: 'CA', city: 'Los Angeles', hospital: [Object] }
  },
  vehicle: { manufacturer: 'Toyota' },
  parents: [ { name: 'John Doe' } ]
}

*/
a-roberts commented 6 months ago

@binury - thank you very much, that works perfectly!

Are you thinking of creating a PR to the main readme? No worries if not as folks could find this as a useful reference. Appreciate your help