Created
April 28, 2022 08:11
-
-
Save ilhamgusti/e9db868eeee76b60da3c9d932877ceed to your computer and use it in GitHub Desktop.
writing mutable object safely
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
/** | |
* | |
* @param o Object to mutate | |
* @param ks array of keys, or string of keys | |
* @param v value to assign | |
* @param sep custom separator if keys is string. ex: ks:"INIxxADALAHxxKEY", sep is: "xx" | |
*/ | |
function mutableSet(o, ks, v, sep = '.') { | |
ks.split && (ks=ks.split(sep)); | |
let i=0, l=ks.length, t=o, x, k; | |
while (i < l) { | |
k = ks[i++]; | |
if (k === '__proto__' || k === 'constructor' || k === 'prototype') break; | |
t = t[k] = (i === l) ? v : (typeof(x=t[k])===typeof(ks)) ? x : (ks[i]*0 !== 0 || !!~(''+ks[i]).indexOf(sep)) ? {} : []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
upgrade version of https://gist.github.com/ilhamgusti/83bed418013bf0fd2eae8023ed47e9bb