Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active October 19, 2017 06:03
Show Gist options
  • Save abhisekp/d6914d5c8e946772e2032646ee7261b3 to your computer and use it in GitHub Desktop.
Save abhisekp/d6914d5c8e946772e2032646ee7261b3 to your computer and use it in GitHub Desktop.
Lodash Methods
  • isNumber - check for number or NaN value
  • isMap - check for Map type
  • isFunction - check for function value
  • isNull - check for null value
  • isNil - check for null or undefined value
  • isNaN - check for NaN value
  • isError - check for Error type
  • isSet - check for Set type
  • isDate - check for Date type
  • take - takes the n number of elements from left
  • takeRight - takes the n number of elements from right
  • takeWhile - starts takes elements from left till predicate function is truthy
  • takeRightWhile - starts takes elements from right till predicate function is truthy
  • slice
  • first or head - gets the first element
  • last - gets the last element
  • initial - gets all but last element
  • tail - gets all but first element

Example

const obj = {
  id: '123',
  from: {
    user: 'abhisekp'
  },
  'from.user': 'Tommy'
}

console.log(
  pickDeepAll(['id', 'from.user', {
    from_user: 'from.user'
  }], obj)
);
/*
{
  from.user: "Tommy",
  from_user: "Tommy",
  id: "123"
}
*/

console.log(
  pickDeepAll('id', obj)
);
/*
{
  id: "123"
}
*/

Algorithm

const pickDeepAll = _.curry((props, obj) => {
	const propList = _.concat([], props);
	const [propStrings, propObjs] = _.partition(_.isString, propList);

	const picked1 = _.pickAll(propStrings, obj);
	const picked2 = _.reduce((pickedObj, propMap) => {
		const mappedObj = _.mapValues(_.get(_, obj), propMap);

		return Object.assign(pickedObj, mappedObj);
	}, {}, propObjs);

	return Object.assign(picked1, picked2);
});
const arr = [
"0002-0002-0003-0004",
"5874-1734-1294-0004",
"4234-9999-1234-1234",
"4346-1234-1004-5884",
"0002-0002-0004-0003"
]
/*
1. split the array elements at `-` to 2D array
[["0002","0002","0003","0004", ..., ...]
2. Parse each inner array elements to numbers
[[2, 2, 3, 4], ..., ...]
3. Sum each array
[11, 8906, 16701, 12468, 11]
*/
const _ = require('lodash/fp');
const sums = _.map(_.flow(
_.split('-'),
_.map(_.toNumber),
_.sum
));
console.log(sums(arr));
//=> [ 11, 8906, 16701, 12468, 11 ]

Frequently used Lodash methods

I use the following methods frequently in the Lodash fp library
  1. curryN
  2. partial
  3. defaults
  4. first
  5. get
  6. concat
  7. filter
  8. every
  9. includes
  10. tap
  11. set
  12. flow
  13. map
  14. pick
  15. constant
  16. identity
  17. noop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment