Skip to content

Instantly share code, notes, and snippets.

@brianswisher
Created July 10, 2019 23:25
Show Gist options
  • Save brianswisher/2ce1ffe3ec08634f78aacd1b7baa31f9 to your computer and use it in GitHub Desktop.
Save brianswisher/2ce1ffe3ec08634f78aacd1b7baa31f9 to your computer and use it in GitHub Desktop.
Easy testing with JavaScript
(()=>{
const test = (result, expect) =>
`${result === expect && '✅' || '🔴'} ${expect}:${result}`
function dynamicNestedObject (total, value) {
const result = {}
const keys = 'abcdefghijklmnopqrstuvwxyz'.substring(0, total).split('')
const lastIndex = keys.length - 1
keys.reduce((o, k, i) => {
const isLastIndex = i === lastIndex
const val = isLastIndex && value || o[k] || {}
return o[k] = val
}, result)
return result
}
console.log(dynamicNestedObject(5, 'cool'))
console.log(test(dynamicNestedObject(3, 'hello').a.b.c, 'hello'))
console.log(test(dynamicNestedObject(4, 'world').a.b.c.d, 'world'))
})()
@brianswisher
Copy link
Author

brianswisher commented Jul 12, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment