Last active
January 21, 2016 20:47
-
-
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
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
| 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