Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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