Created
November 15, 2017 00:38
-
-
Save jmakeig/cfad4c55f959b2657acfad7df8fcb210 to your computer and use it in GitHub Desktop.
JavaScript shallow clone
This file contains hidden or 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
/** | |
* Creates a shallow copy of an Object or an Array, such that, | |
* `a !== shallowClone(a)`, but `a.b === shallowClone(a).b`, where `b` | |
* is not a primitive value. Deep cloning is out of scope here. | |
* | |
* @param {*} item - any “simple” `Object` or `Array` | |
* @return {*} | |
* @throws {TypeError} - if an Object does not directly inherit from | |
* `Object.prototype` or `null` | |
*/ | |
function shallowClone(item) { | |
if ('object' !== typeof item) return item; | |
if (Array.isArray(item)) return [...item]; | |
const isSimpleObject = x => | |
[null, Object.prototype].some(type => type === Object.getPrototypeOf(x)); | |
if (!isSimpleObject(item)) { | |
throw new TypeError(); | |
} | |
return Object.assign(Object.create(null), item); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment