Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active December 28, 2020 01:42
Show Gist options
  • Save VitorLuizC/01042b3455bf8a2b8ba5ef86d6a1c0d8 to your computer and use it in GitHub Desktop.
Save VitorLuizC/01042b3455bf8a2b8ba5ef86d6a1c0d8 to your computer and use it in GitHub Desktop.
Some lodash functions replaced by ES2015+

_.compact([ ...list ])

compact function just returns a new Array without falsy values.

A filter could do the trick using a simple isTruthy expression.

[ ...list ].filter(value => value)
const compact = (list) => [ ...list ].filter((value) => value);

_.get(object, path, placeholder)

new Function('o', 'p', `try{return o.${path}}catch(_){return p}`)(object, placeholder)
const get = (object, path, placeholder = null) => {
  try {
    const value = new Function('object', `return object.${path}`)(object);
    return value !== undefined ? value : placeholder;
  } catch (err) {
    return placeholder;
  }
};

_.unique([ ...list ])

[ ...new Set(list) ]
const unique = (list) => [ ...new Set(list) ];
@caub
Copy link

caub commented Dec 26, 2020

your _.get is terrible, just have const get = (o, path) = path.split('.').reduce((acc, k) => acc[k], o)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment