Created
October 16, 2018 17:25
-
-
Save westc/33996c4fe080b5241702cdbc4986e4c8 to your computer and use it in GitHub Desktop.
YourJS candidate function: swapProps()
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
/** | |
* 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