Created
January 9, 2020 22:14
-
-
Save nxta/f51bc389734d707cc8918a19ea079c7a to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Helpers for Flarum | |
* | |
* Allows you to do the following | |
* setDeep(vdom, 'attrs.style.borderColor', '#f00') | |
* mergeDeep(this.props, {className: 'Class', params: {q: null}}) | |
*/ | |
// https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge | |
/** | |
* Simple object check. | |
* @param item | |
* @returns {boolean} | |
*/ | |
function isObject(item) { | |
return (item && typeof item === 'object' && !Array.isArray(item)); | |
} | |
/** | |
* Deep merge two objects. | |
* @param target | |
* @param ...sources | |
*/ | |
export function mergeDeep(target, ...sources) { | |
if (!sources.length) return target; | |
const source = sources.shift(); | |
if (isObject(target) && isObject(source)) { | |
for (const key in source) { | |
if (isObject(source[key])) { | |
if (!target[key]) Object.assign(target, { [key]: {} }); | |
mergeDeep(target[key], source[key]); | |
} else { | |
Object.assign(target, { [key]: source[key] }); | |
} | |
} | |
} | |
return mergeDeep(target, ...sources); | |
} | |
// https://stackoverflow.com/questions/6842795/dynamic-deep-setting-for-a-javascript-object | |
export default function setDeep(obj, path, value) { | |
const a = path.split('.'); | |
let o = obj; | |
let n; | |
while (a.length - 1) { | |
n = a.shift(); | |
if (!(n in o)) o[n] = {}; | |
o = o[n]; | |
} | |
o[a[0]] = value; | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment