ES5 + Lodash (Coderpad) Flashcards
Max value of a collection or object
_.max({ 5: ‘a’, 3: ‘b’ }, (value, key) => key)
Repeat a string X times
_.repeat('*', 3); // → '***'
_.repeat(‘abc’, 2);
// → ‘abcabc’
~~~
_.repeat(‘abc’, 0);
// → ‘’
~~~
Are any elements of this object or truthy?
_.some(collection)
The default value of the predicate parameter is _.identity.
Create the range [-1, 0, 1]
_.range(-1, 2)
Optional third param: step
Remove an array element from an array.
_.reject(collection, arr => _.isEqual(arr, toRemove))
- _.without() uses ES SameValueZero, which compares if objects are the exact same thing.*
- _.remove mutates!*
Check if n is between 0 and 4.
_.inRange(n, 0, 5)
Ranges seem to be exclusive.
Add an array to an array without mutation
[1, [0, 1]].concat([[0, 0]])
=> [1, [0, 1], [0, 0]]
Generate a new string with a char at index i replaced
str.slice(0, i) + newChar + str.slice(i + 1, str.length)
Add a list of elements to an array, return the array
List([1, 2]).push(1, 2)
Class with a class method
class Dog { static bark() {} }
Class with a class variable
class Dog {} Dog.type = 'awesome'
Range from 0 to n, inclusive
Range(0, n + 1)
Range from 0 to n by 2, inclusive
Range(0, n + 1, 2)
Range from n to 0, inclusive
Range(n, -1) // end is always exclusive
Repeat value ‘a’ n times
Repeat(‘a’, 5)
Get from a hash, or default to 0
Map().get(‘a’, 0)
Head/first, rest, initial, last?
Yup, all those are methods.
Falsey values?
false 0 “” null undefined NaN
Cast to int
Number.parseInt(‘13a’) // Forgiving: NaN only when first char isn’t number
=> 13
Inspect class/instance methods, exclude inherited
Object.getOwnPropertyNames(Number)
Object.getOwnPropertyNames(Number.prototype)
Inspect instance methods, include inherited
// Hard. Use Object.getOwnPropertyNames
Switch statement
switch (obj) { case value: statement; break; case value: statement; break; default: statement; break; // Under the hood: obj === value }
Read file
fs.readFile(file, ‘utf8’, (err, file) => {})
Read lines of file
fs.readFile(file, ‘utf8’, (err, file) => { file.split(“\n”) })
Trim whitespace from both sides of a string
” a “.trim()
Trim X from end of string
‘xxabcxx’.replace(/x+$/, ‘’)
=> ‘xxabc’
Detect if beginning/end of string matches
‘abc’.endsWith(‘c’) // startsWith
Create a RegExp with interpolation
new RegExp(str, “gim”) // global, ignore case, multiline
Detect if string matches a RegExp
/\w\s(\w+)/.test(“Jason Benn”) // RegExp method
Grab nth match group from string
/\w+\s(\w+)/.exec(‘Jason Benn’)[1]
Find index of regex match
“Jason Benn”.search(/\w\s(\w+)/) // Str method
Sort a map by a criteria
Map().sortBy((v, k, iter) => {})
Filter a map by a criteria
map.filter((v, k, iter) => {})
All elements of an array are truthy
[].every()
Any element of an array is truthy
[].some()
Initialize a date to a date object
new Date(‘…’)
Display a date in a particular format
d.getHours(), d.getDate(), d.getMonth()+1, d.getFullYear()