Skip to content

Instantly share code, notes, and snippets.

@dszakallas
Last active April 13, 2016 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dszakallas/26fb939f0fb81cc1f8a4 to your computer and use it in GitHub Desktop.
Save dszakallas/26fb939f0fb81cc1f8a4 to your computer and use it in GitHub Desktop.
/* The MIT License (MIT) Copyright (c) 2016 David Szakallas */
/*
Variate an object or array!
Object:
{
bananas: [1, 2],
apples: [3, 4]
}
will become:
[
{ banana: 1, apple: 3 },
{ banana: 1, apple: 4 },
{ banana: 2, apple: 3 },
{ banana: 2, apple: 4 }
]
*/
'use strict'
const pluralize = require('pluralize')
const reduce = require('lodash.reduce')
const assign = require('lodash.assign')
const set_ = require('lodash.set')
function * iterate (value, key) {
if (Array.isArray(value)) {
const name = pluralize(key, 1)
for (const item of value) {
yield set_({}, `${name}`, item)
}
} else {
yield set_({}, `${key}`, value)
}
}
function variations (object) {
return (reduce(object, (partials, value, key) => {
return function * () {
for (const partial of partials()) {
for (const item of iterate(value, key)) {
yield assign({}, partial, item)
}
}
}
}, function * () { yield { } }))()
}
module.exports = variations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment