Created
July 24, 2017 01:01
-
-
Save N0taN3rd/db64582fb2431aaa72a1020f12e4392c to your computer and use it in GitHub Desktop.
JS Class __proto__ Proxy
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
| function sortAscending ([ k1, v1 ], [ k2, v2 ]) { | |
| if (v1 < v2) { | |
| return -1 | |
| } | |
| if (v1 > v2) { | |
| return 1 | |
| } | |
| return 0 | |
| } | |
| function sortDescending ([ k1, v1 ], [ k2, v2 ]) { | |
| if (v1 < v2) { | |
| return 1 | |
| } | |
| if (v1 > v2) { | |
| return -1 | |
| } | |
| return 0 | |
| } | |
| module.exports = class Counter { | |
| constructor () { | |
| this.values = {} | |
| // let self = this | |
| this.entries = function () { | |
| return Object.entries(this.values) | |
| } | |
| this.sortedEntries = function (decreasing = false) { | |
| let e = Array.from(this.entries()) | |
| if (decreasing) { | |
| e.sort(sortDescending) | |
| } else { | |
| e.sort(sortAscending) | |
| } | |
| return e[ Symbol.iterator ]() | |
| } | |
| this[ Symbol.iterator ] = function * () { | |
| yield * Object.entries(this.values) | |
| } | |
| this.sorted = function (compare = sortAscending) { | |
| let e = Array.from(this.entries()) | |
| e.sort(compare) | |
| return e[ Symbol.iterator ]() | |
| } | |
| this.__proto__ = new Proxy(this.values, { | |
| set (me, key, value) { | |
| if (typeof value !== 'number') { | |
| throw new TypeError(`the value of ${key} was ${typeof value}, expected number`) | |
| } | |
| me[ key ] = value | |
| return true | |
| }, | |
| get (me, key) { | |
| let v = me[ key ] | |
| if (v === undefined || v === null) { | |
| me[ key ] = 0 | |
| } | |
| return me[ key ] | |
| }, | |
| has (me, prop) { | |
| return prop in me | |
| }, | |
| ownKeys (me) { | |
| return Reflect.keys(me) | |
| }, | |
| getOwnPropertyDescriptor (target, prop) { | |
| return Reflect.getOwnPropertyDescriptor(target, prop) | |
| } | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment