Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Created November 15, 2017 00:38
Show Gist options
  • Save jmakeig/cfad4c55f959b2657acfad7df8fcb210 to your computer and use it in GitHub Desktop.
Save jmakeig/cfad4c55f959b2657acfad7df8fcb210 to your computer and use it in GitHub Desktop.
JavaScript shallow clone
/**
* 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