Skip to content

juliancoleman/you-should-know-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 

Repository files navigation

you-should-know-cheatsheet

A cheatsheet of things you should know as a JS developer

(examples in TS for type clarity)

Arrays

Get max value of array

Without spread:

const arr: number[] = [1, 2, 3, 4, 5];
Math.max.apply(null, arr); // => 5

With spread:

Math.max(...arr);

Get min value of array

Change max to min in the example above.

Sum all numbers in array

const arr: number[] = [1, 2, 3, 4, 5];
const sum = (a: number, b: number) => a + b;
arr.reduce(sum, 0);

Filter odd numbers in array

Getting the odd numbers of an array is easy.

const odds = (arr: number[]) =>
  arr.filter(v => v & 1);

Filter even numbers in array

Getting evens is also easy!

const evens = (arr: number[]) =>
  arr.filter(v => !(v & 1));

Add an item to the beginning of the array

Unfortunately, #unshift() returns the new length of the array, not the actual array.

Array.prototype.unshift()

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];

Add an item to the end of the array

#push() also returns the new length of the array, not the actual array.

Array.prototype.push()

The above example works with this as well. Just replace unshift with push.

Or, again, even simpler with spread:

const newArr = [...arr, item];

Add an item anywhere in the array

Oddly returns an empty array if you add an item without removing any items.

Array.prototype.splice()

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;
}  

Numbers

Formatting money

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)}`;

About

A cheatsheet of things you should know as a JS developer

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published