Skip to content

Instantly share code, notes, and snippets.

@westc
Created October 16, 2018 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/33996c4fe080b5241702cdbc4986e4c8 to your computer and use it in GitHub Desktop.
Save westc/33996c4fe080b5241702cdbc4986e4c8 to your computer and use it in GitHub Desktop.
YourJS candidate function: swapProps()
/**
* Swaps the specified properties between the target object and the source object.
* @param {*} target
* Target object from which the specified properties will be swapped.
* @param {*} source
* Source object from which the specified properties will be swapped.
* @param {Array<number|string>} keys
* Array of keys for the properties that should be swapped between source and
* target.
* @param {boolean=} [opt_dontDelete=false]
* Indicates whether properties that dont exist should be deleted between objects.
* If `true`, non-existent properties will be set to `undefined`.
* @returns {*}
* Returns a reference to `target`.
*/
function swapProps(target, source, props, opt_dontDelete) {
source = Object(source);
for (var t, copyToSource, prop, oTarget = Object(target), i = props.length; i--;) {
prop = props[i];
copyToSource = prop in oTarget;
t = oTarget[prop];
if ((prop in source) || opt_dontDelete) {
oTarget[prop] = source[prop];
}
else {
delete oTarget[prop];
}
if (copyToSource || opt_dontDelete) {
source[prop] = t;
}
else {
delete source[prop];
}
}
return target;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment