Skip to content

Instantly share code, notes, and snippets.

@kutyel
Last active August 15, 2017 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kutyel/dd935bccd2acb4537cee to your computer and use it in GitHub Desktop.
Save kutyel/dd935bccd2acb4537cee to your computer and use it in GitHub Desktop.
reduce() vs Universe
// reduce() awesomeness
const a = [1, 2, 3, 4, 5, 5, 3]
const b = [{ key: 1, value: 'a' }, { key: 2, value: 'b' }]
const c = [Promise.resolve(), Promise.resolve(), Promise.resolve()]
const d = ['a', 'a', 'a', 'a', 'a']
// Max
a.reduce((x, y) => x > y ? x : y) // > 5
// Min
a.reduce((x, y) => x < y ? x : y) // > 1
// Sum
a.reduce((x, y) => x += y, 0) // > 23
// Unique
a.reduce((x, y) => x.indexOf(y) === -1 ? x.concat(y) : x, []) // > [1, 2, 3, 4, 5]
// Collection to Object
b.reduce((o, v) => (o[v['key']] = v['value'], o), {}) // > Object { 1: "a", 2: "b" }
// Promise chaining
c.reduce((cur, next) => cur.then(next), Promise.resolve()) // > Promise
// Check if all elements in an array are the same
!!d.reduce((x, y) => x === y ? x : null) // > true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment