Last active
March 29, 2018 21:34
-
-
Save thcolin/4e239fdb7096c8ab26c65925660c4c95 to your computer and use it in GitHub Desktop.
🦖 Duno - First attempt to create an Immutable lib with easy API
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
function duno(root, diff, index) { | |
let dunoed = Object.assign({}, root) | |
for (let key in diff) { | |
switch (typeof diff[key]) { | |
case 'function': | |
dunoed[key] = diff[key](dunoed[key], dunoed) | |
break | |
default: | |
dunoed[key] = diff[key] | |
break | |
} | |
} | |
return dunoed | |
} | |
let state = { | |
entities: { | |
abc: { | |
id: 'abc', | |
pseudo: 'abc' | |
}, | |
def: { | |
id: 'def', | |
pseudo: 'def' | |
} | |
}, | |
result: ['abc', 'def'] | |
} | |
let dunoed | |
// edit a key in a 2 depth deep object | |
dunoed = duno(state, { | |
entities: self => duno(self, { | |
abc: self => duno(self, { | |
pseudo: 'lol' | |
}) | |
}) | |
}) | |
console.log(dunoed) | |
// edit a key in a 2 depth deep object (advanced) | |
dunoed = duno(state, { | |
entities: self => duno(self, { | |
abc: (self, root) => duno(root.abc, { | |
pseudo: 'lol' | |
}) | |
}) | |
}) | |
console.log(dunoed) | |
// delete an entry | |
dunoed = duno(state, { | |
entities: self => Object | |
.keys(self) | |
.filter(key => key !== 'abc') | |
.reduce((obj, key) => Object.assign(obj, { [key]: self[key] }), {}), | |
result: self => self.filter(value => value !== 'abc') | |
}) | |
console.log(dunoed) | |
// replace a key in an 1 depth deep object and a value in an array | |
dunoed = duno(state, { | |
entities: self => Object | |
.keys(self) | |
.filter(key => key !== 'abc') | |
.concat(['ghi']) | |
.reduce((obj, key) => Object.assign(obj, { [key]: | |
key === 'ghi' ? Object.assign(self.abc, { id: 'ghi' }) : self[key] | |
}), {}), | |
result: self => self.map(value => value === 'abc' ? 'ghi' : value) | |
}) | |
console.log(dunoed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment