ultrawidify/src/ext/lib/ObjectCopy.ts

85 lines
2.7 KiB
TypeScript
Raw Normal View History

import Debug from '../conf/Debug';
class ObjectCopy {
static addNew(current, newValues){
// clone target
2021-02-18 22:38:32 +01:00
let out = JSON.parse(JSON.stringify(newValues));
if(! current) {
2018-08-29 00:41:26 +02:00
if(Debug.debug) {
console.log("[ObjectCopy::addNew] There's no existing value. Returning target value.");
}
return out;
}
2021-02-18 22:38:32 +01:00
for(let k in out) {
// if current key exist, replace it with existing value. Take no action otherwise.
if(current[k]) {
// Types and constructors of objects must match. If they don't, we always use the new value.
if(typeof out[k] === typeof current[k] && out[k].constructor === current[k].constructor) {
// objects are special, we need to check them recursively.
if(out[k] && typeof out[k] === 'object' && out[k].constructor === Object ) {
if(Debug.debug && Debug.settings) {
console.log("[ObjectCopy::addNew] current key contains an object. Recursing!")
}
out[k] = this.addNew(current[k], out[k]);
} else {
out[k] = current[k];
}
}
}
}
2018-09-22 22:50:32 +02:00
// add the values that would otherwise be deleted back to our object. (We need that so user-defined
// sites don't get forgotten)
2021-02-18 22:38:32 +01:00
for(let k in current) {
2018-09-22 22:50:32 +02:00
if (! out[k]) {
out[k] = current[k];
2018-09-22 22:50:32 +02:00
}
}
return out;
}
static overwrite(current, newValues){
2021-02-18 22:38:32 +01:00
for(let k in newValues) {
2019-07-05 23:45:29 +02:00
// if current key exist, replace it with existing value. Take no action otherwise.
if (current[k] !== undefined) {
2019-07-05 23:45:29 +02:00
// Types and constructors of objects must match. If they don't, we always use the new value.
if (typeof newValues[k] === typeof current[k] && newValues[k].constructor === current[k].constructor) {
2019-07-05 23:45:29 +02:00
// objects are special, we need to check them recursively.
if(current[k] && typeof current[k] === 'object' && current[k].constructor === Object ) {
2019-07-05 23:45:29 +02:00
if(Debug.debug && Debug.settings) {
console.log("[ObjectCopy::addNew] current key contains an object. Recursing!")
}
current[k] = this.overwrite(current[k], newValues[k]);
2019-07-05 23:45:29 +02:00
} else {
current[k] = newValues[k];
2019-07-05 23:45:29 +02:00
}
} else {
current[k] = newValues[k];
2019-07-05 23:45:29 +02:00
}
}
else if (newValues[k] !== undefined) {
current[k] = newValues[k];
}
2019-07-05 23:45:29 +02:00
}
return current;
2019-07-05 23:45:29 +02:00
}
static pruneUnused(existing, target, ignoreKeys) {
// TODO: implement at some other date
// existing: object that we have.
// target: object that we want
// ignoreKeys: if key is an object, we don't recursively call this function on that key
}
}
export default ObjectCopy;