Skip to content

Instantly share code, notes, and snippets.

@ryan-haskell
Last active November 15, 2017 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryan-haskell/6f37f4c42313479d266a5fb04b2454e3 to your computer and use it in GitHub Desktop.
Save ryan-haskell/6f37f4c42313479d266a5fb04b2454e3 to your computer and use it in GitHub Desktop.
Used for expanding KeystoneJS fields, and flattening the response
const getRange = (start, end) => {
let list = []
if (start <= end) {
for (let i = start; i <= end; i++)
list.push(i)
}
return list
}
const RepeatableField = (fields, prefix) => ({
expand: (num) =>
getRange(1, num)
.reduce((obj, num) => {
obj[prefix + num] = Object.assign({}, fields)
return obj
}, {}),
expandDependsOn (num, field) {
const original = this.expand(num)
const keys = Object.keys(original)
return keys.reduce((obj, key, index) => {
obj[key].dependsOn = {
[field]: getRange(index + 1, num)
}
return obj
}, original)
},
flatten: (original) =>
Object.keys(original).reduce((obj, key) => {
if (key.indexOf(prefix) === 0) {
obj[prefix].push(original[key])
} else {
obj[key] = original[key]
}
return obj
}, {
[prefix]: []
})())
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment