Last active
June 14, 2021 08:06
-
-
Save akkerman/5fa08811c22990de9256e97e30de785e to your computer and use it in GitHub Desktop.
functional javascript recipes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// transform array of objects to a dictionary object | |
const dict = arr => arr.reduce((result, item) => ({ ...result, [item.id]: item }), {}) // empty object as start value | |
// flatten an array of arrays | |
const flattened = arr => arr.reduce((result, arr) => result.concat(arr), []) // empty array as start value | |
// check if all elements in an array are in a source array | |
const hasAll = source => arr => arr.every(item => source.includes(item)) | |
// check if any element in an array is in a source array | |
const hasAny = source => arr => arr.some(item => source.includes(item)) | |
// sleep using await // use: await sleep(150) | |
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) | |
// apply an array of functions to a value | |
const pipe = (...fns) => value => fns.reduce((x, f) => f(x), value) | |
// apply a function multiple times on a value | |
const applyN = (f, n) => pipe(...Array(n).fill(f)) |
Author
akkerman
commented
Feb 18, 2021
function arrayToDict ({ keyProp, valueProp = null, array }) {
const mapper = valueProp
? item => [item[keyProp], item[valueProp]]
: item => [item[keyProp], item]
return Object.fromEntries(array.map(mapper))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment