Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active July 7, 2021 20:53
Show Gist options
  • Save OliverJAsh/254c9cd45a4cdf3f9450 to your computer and use it in GitHub Desktop.
Save OliverJAsh/254c9cd45a4cdf3f9450 to your computer and use it in GitHub Desktop.
JS utils
const head = array => array[0];
const zip = (...arrays) => (
head(arrays).map((value, index) => arrays.map(otherArray => otherArray[index]))
);
const map = (collection, mapFn) => (
Object.keys(collection).map(key => mapFn(collection[key], key))
);
const reduce = (collection, reduceFn, seed) => (
Object.keys(collection).reduce((acc, key) => {
const value = collection[key];
return reduceFn(acc, value, key);
}, seed)
);
const mapKeys = (collection, mapFn) => (
reduce(collection, (acc, value, key) => {
acc[mapFn(value, key)] = value;
return acc;
}, {})
);
const contains = (array, itemToFind) => array.some(item => item === itemToFind);
const range = (start, end) => (
Array.from({ length: end - start }, (x, i) => i + start)
);
// OR
const range = (start, end) => Array(end - start).fill().map((x, i) => i + start)
const flatten = (xs) => xs.reduce((acc, value) => acc.concat(value), [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment