I keep on forgetting some cool declarative methods in JS, so this is a reminder compilation for me to refresh my memory as I encounter them doing coding challenges.
-
Array.prototype.sort(compareFn)
. Mutates array "in place" after converting values to string and comparing UTF-16 code unit values. Values are sorted ascending. If you don't want to mutate the array, usetoSorted
.compareFn
is called witha
andb
and should return a negative number ifa
is smaller thanb
, positive ifa
is bigger thanb
or 0 if they are the same. IfcompareFn
is not supplied the array is sorted after comparing the values to their string form. More here. -
Math.max(value1, value2, etc.)
andMath.min(value1, value2, etc.)
. If the array has few elements, you can use it likeMath.max(...array)
. It is best to usereduce
:
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
-
String.prototype.repeat(count)
. Repeats a string acount
number of times. i.e.'Hello'.repeat(3)
returnHelloHelloHello
. -
Array.prototype.some(cb)
- returnstrue
if one item in the array returns a truthy value when the callback is called upon orfalse
otherwise. It stops iterating as soon as it find an element that returns a truthy value. -
0 + true
is1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus#usage_with_non-numbers -
new Set([1,1,3,2,2,3,4])
will get rid of the duplicates and return[1,3,2,4]
because aset
can't have duplicates. -
address.split('@').pop()
will return the domain in an email even when there are 2@
s.
Regex stuff
-
/^\d*/
< match any series of digits at the start. You can then dostring.match(/^\d*/)
to find a prefix made up of digits only. -
'string'.match(regex)
will return the matches. If theg
flag is used, it returns an array with the matches. If not, just the first match. i.e.'010010000110010101101100011011000110111100100001'.match(/.{1,8}/g)
will return an array of bytes. -
String.fromCharCode(charCode)
returns the ASCII string attached to the charCode.
Binary numbers
-
parseInt(binaryNumberString, 2)
will return the integer of the number in whatever base we say. The example is base 2.