-
-
Save VinayaSathyanarayana/00bfe5f7a2914c7d10430b63628837a1 to your computer and use it in GitHub Desktop.
Used for expanding KeystoneJS fields, and flattening the response
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
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