Functional JS

Pere Sola - Jan 28 - - Dev Community

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, use toSorted. compareFn is called with a and b and should return a negative number if a is smaller than b, positive if a is bigger than b or 0 if they are the same. If compareFn is not supplied the array is sorted after comparing the values to their string form. More here.
  • Math.max(value1, value2, etc.) and Math.min(value1, value2, etc.). If the array has few elements, you can use it like Math.max(...array). It is best to use reduce:
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
Enter fullscreen mode Exit fullscreen mode
  • String.prototype.repeat(count). Repeats a string a count number of times. i.e. 'Hello'.repeat(3) return HelloHelloHello.
  • Array.prototype.some(cb) - returns true if one item in the array returns a truthy value when the callback is called upon or false otherwise. It stops iterating as soon as it find an element that returns a truthy value.
  • 0 + true is 1 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 a set 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 do string.match(/^\d*/) to find a prefix made up of digits only.
  • 'string'.match(regex) will return the matches. If the g 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.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .