Skip to content

Instantly share code, notes, and snippets.

@dtipson
Last active January 21, 2016 20:47
Show Gist options
  • Select an option

  • Save dtipson/821068d16cf890b6bf48 to your computer and use it in GitHub Desktop.

Select an option

Save dtipson/821068d16cf890b6bf48 to your computer and use it in GitHub Desktop.
Using Symbols to extend native prototypes in a way that cannot possibly clash with native extensions added in the future
const e = {};//define a store of possible props we want to add
(function(e){
const empty = Symbol('empty');
const _empty = ()=>[];
const flatten = Symbol('flatten');
function _flatten(){
return this.reduce( (a,b) => a.concat(b), []);
}
Object.defineProperty(Array.prototype, empty,{
value: _empty,
writable: true,
configurable: true,
enumerable: false
});
Object.defineProperty(Array.prototype, flatten,{
value: _flatten,
writable: true,
configurable: true,
enumerable: false
});
Object.assign(e,{empty,flatten});
})(e);
//test data
const testArr = [4,5,6];
const testArr2 = [4,5,6,[5,6,7],[3,4]];
//usage: we're calling method that are defined on a Symbol key, using the prop lookup
testArr[e.empty]();//-> []
testArr2[e.flatten]();//-> [4, 5, 6, 5, 6, 7, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment