Skip to content

Instantly share code, notes, and snippets.

@maxired
Created January 22, 2019 15:00
Show Gist options
  • Save maxired/8de32f932d915a5a2c61ff15c4fcfd0d to your computer and use it in GitHub Desktop.
Save maxired/8de32f932d915a5a2c61ff15c4fcfd0d to your computer and use it in GitHub Desktop.
Set if needed
export const setPath = ([key, ...next], value, obj) => {
if (next.length === 0) {
return {...obj, [key]: value };
}
return {...obj, [key]: setPath(next, value, obj[key]) };
};
export const getPath = ([key, ...next], obj) => {
if (next.length === 0) {
return obj[key];
}
return getPath(next, obj);
}
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b)
export const setPathIfNeeded = (path, value, obj) => {
const currentValue = getPath(path, obj);
if (isEqual(currentValue, obj)) return obj;
return setPath(path, value, obj);
}
export const set = (path, value, obj) => setPath(path.split('.'), value, obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment