Last active
November 15, 2017 17:41
-
-
Save ryan-haskell/6f37f4c42313479d266a5fb04b2454e3 to your computer and use it in GitHub Desktop.
Used for expanding KeystoneJS fields, and flattening the response
This file contains 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
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