Skip to content

Instantly share code, notes, and snippets.

@sangkukbae12
Created May 15, 2020 23:21
Show Gist options
  • Save sangkukbae12/3738833c1f138c6a704dd1e07599b4cc to your computer and use it in GitHub Desktop.
Save sangkukbae12/3738833c1f138c6a704dd1e07599b4cc to your computer and use it in GitHub Desktop.
Pure JavaScript Functions as a Replacement for Lodash
// 1. find
const users = [
{ 'user': 'joey', 'age': 32 },
{ 'user': 'ross', 'age': 41 },
{ 'user': 'chandler', 'age': 39 }
]
// Native
users.find(function (o) { return o.age < 40; })
//lodash
_.find(users, function (o) { return o.age < 40; })
// 2. filter
const numbers = [10, 40, 230, 15, 18, 51, 1221]
_.filter(numbers, num => num % 3 === 0)
numbers.filter(num => num % 3 === 0)
// 3. first and rest
const names = ["first", "middle", "last", "suffix"]
const firstName = _.first(names)
const otherNames = _.rest(names)
const [firstName, ...otherNames] = names
console.log(firstName) // 'first'
console.log(otherNames) // [ 'middle', 'last', 'suffix' ]
// 4. each
_.each([1, 2, 3], (value, index) => {
console.log(value)
})
[1, 2, 3].forEach((value, index) => {
console.log(value)
})
_.forEach({ 'a': 1, 'b': 2 }, (value, key) => {
console.log(key);
});
({ 'a': 1, 'b': 2 }).forEach((value, key) => { // !error
console.log(key);
});
// 5. every
const elements = ["cat", "dog", "bat"]
_.every(elements, el => el.length == 3)
elements.every(el => el.length == 3) //true
// 6. some
const elements = ["cat", "dog", "bat"]
_.some(elements, el => el.startsWith('c'))
elements.some(el => el.startsWith('c'))
// 7. includes
const primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,97]
_.includes(primes, 47)
primes.includes(79)
// 8. uniq
var elements = [1,2,3,1,2,4,2,3,5,3]
_.uniq(elements)
[...new Set(elements)]
// 9. compact
var array = [undefined, 'cat', false, 434, '', 32.0]
_.compact(array)
array.filter(Boolean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment