Skip to content

Instantly share code, notes, and snippets.

@akkerman
Last active June 14, 2021 08:06
Show Gist options
  • Save akkerman/5fa08811c22990de9256e97e30de785e to your computer and use it in GitHub Desktop.
Save akkerman/5fa08811c22990de9256e97e30de785e to your computer and use it in GitHub Desktop.
functional javascript recipes
// 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))
@akkerman
Copy link
Author

function arrayToDict ({ keyProp, valueProp = null, array }) {
  const reducer = valueProp
    ? (result, item) => ({ ...result, [item[keyProp]]: item[valueProp] })
    : (result, item) => ({ ...result, [item[keyProp]]: item })

  return array.reduce(reducer, {}) // empty object as start value
}

@akkerman
Copy link
Author

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