Last active
April 13, 2016 21:44
-
-
Save dszakallas/26fb939f0fb81cc1f8a4 to your computer and use it in GitHub Desktop.
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
/* 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