Skip to content

Instantly share code, notes, and snippets.

@wbobeirne
Created July 12, 2017 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbobeirne/e944186117397ca5c63b11aa0aed2202 to your computer and use it in GitHub Desktop.
Save wbobeirne/e944186117397ca5c63b11aa0aed2202 to your computer and use it in GitHub Desktop.

_.map

Pretty much identical IMO.

// Lodash
const listOfAttrs = _.map(listOfObjects, (obj) => obj.attr);

// JS
const listOfAttrs = listOfObjects.map((obj) => obj.attr);

_.isNil

Lol the source is literally value == null

// Lodash
if (_.isNil(value)) { /* stuff */ }

// JS (the right way)
if (value === null || value === undefined) { /* stuff */ }

// JS (the identical way)
if (value == null) { /* stuff */ }

_.size

Ok what? Why would I need to handle both arrays and object key count interchangably? I feel like your code should be specific to which of those you're dealing with. But I agree that object's way of doing it is a little verbose.

It's also worth being aware of just how "nice" this function is because it's totes kosh with null / undefined. I feel like I'd rather explicitly code that case, or fail when that happens.

// Lodash
const size = _.size(someVar);

// JS (arrays and strings)
const size = someVar.length;

// JS (objects)
const size = Object.keys(someObj).length;

_.get

Just read a real good article about this WRT redux over here. But regardless, yeah I find this one to be a pain. I really miss coffeescript's existential operator. But I've definitely been drinking some amount of redux koolaid when I say that flatter is better where you can choose. Not to mention missing different depths of an object usually mean different things went wrong, so handling them differently is sometimes important. And similarly to size, I like to fail loud. But at this point, I'm just rationalizing.

// Lodash
const someKey = _.get(someObj, "a.b.c");

// JS
const someKey = (someObj && someObj.a && someObj.a.b) && someObj.a.b.c;
# Coffeescript (Hellz yeah)
someKey = someObj?.a?.b?.c

_.filter

Similar to map, no real difference IMO.

// Lodash
const filteredArray = _.filter(allArray, (item) => !!item);

// JS
const filteredArray = allArray.filter((item) => !!item);

_.includes and _.find

String and Array already have identical .includes functions (Same comparison and everything!), Array has a .find function, so Lodash only wins out on objects. But it definitely wins.

// Lodash
if (_.includes(obj, searchValue)) { /* stuff */ }

// JS (Array)
const hasValue = Object.keys(obj).reduce((prev, key) => prev || obj[key] === someVal);
if (hasValue) { /* stuff */ }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment