Skip to content

Instantly share code, notes, and snippets.

@benji6
Created January 18, 2016 20:07
Show Gist options
  • Save benji6/f3fd97830f490cdcae2d to your computer and use it in GitHub Desktop.
Save benji6/f3fd97830f490cdcae2d to your computer and use it in GitHub Desktop.
// there's got to be a better name for this function
const analyze = (xForms, data) => Object.keys(xForms).reduce(
(acc, key) => Object.assign(acc, {[key]: xForms[key](data)}),
{}
)
// it allows application of multiple transformations to a single value
// and combines the results of those transformations into a single object
const rectangleSideLengths = [3, 4]
const area = ([a, b]) => a * b
const diagonalLength = ([a, b]) => Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))
const result = analyze({area, diagonalLength}, rectangleSideLengths)
console.log(result) // => {area: 12, diagonalLength: 5}
// I think it could be especially useful for manipulating objects received over
// APIs as they are sometimes not in the desired shape, contain superflous
// information, or require processing to derive useful values.
// I think it may be more elegant to do this by composing small
// transformations than to tackle the problem in a single function
// I have no idea what to call this, but it separates transformations
// from the building up of a result so now we can combine our transformations
// to yield any sort of value we choose
const combineTransformers = (xForms, combiner, initialValue, data) => xForms
.reduce((acc, xForm) => combiner(acc, xForm(data)), initialValue)
// Replicating the analyze example
const rectangleSideLengths = [3, 4]
const area = ([a, b]) => ({area: a * b})
const diagonalLength = ([a, b]) => ({
diagonalLength: Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))
})
const result = combineTransformers(
[area, diagonalLength],
Object.assign,
{},
rectangleSideLengths
)
console.log(result) // => {area: 12, diagonalLength: 5}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment