A cheatsheet of things you should know as a JS developer
(examples in TS for type clarity)
Without spread:
const arr: number[] = [1, 2, 3, 4, 5];
Math.max.apply(null, arr); // => 5
With spread:
Math.max(...arr);
Change max
to min
in the example above.
const arr: number[] = [1, 2, 3, 4, 5];
const sum = (a: number, b: number) => a + b;
arr.reduce(sum, 0);
Getting the odd numbers of an array is easy.
const odds = (arr: number[]) =>
arr.filter(v => v & 1);
Getting evens is also easy!
const evens = (arr: number[]) =>
arr.filter(v => !(v & 1));
Unfortunately, #unshift()
returns the new length of the
array, not the actual array.
You could return the full array by wrapping in a closure:
function prepend(arr: any[], item: any) {
arr.unshift(item);
return arr;
}
Or even simpler with spread:
const newArr = [item, ...arr];
#push()
also returns the new length of the array, not the
actual array.
The above example works with this as well. Just replace
unshift
with push
.
Or, again, even simpler with spread:
const newArr = [...arr, item];
Oddly returns an empty array if you add an item without removing any items.
You can insert (without removing items) with the following:
function insertAtIndex(arr: any[], val: any, index: number) {
const deleteCount: number = 0;
arr.splice(index, deleteCount, val);
return arr;
}
Let's suppose I passed you the number 3.1
. How would I get
it to read $3.10
?
Note: JavaScript rounds to the nearest integer, leaving off trailing zeros.
const format = (f64: number): string => `$${f64.toFixed(2)}`;