Created
June 1, 2020 14:46
-
-
Save ardeshireshghi/080d6318eb13f355369030053af387b0 to your computer and use it in GitHub Desktop.
Tuple data structure JS
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 Tuple = (() => { | |
const handler = { | |
construct(target, args) { | |
const obj = new target(...args); | |
return new Proxy(obj, { | |
get: function (target, prop) { | |
if (typeof target._data[prop] !== 'function') { | |
return target._data[prop]; | |
} else { | |
return (...args) => { | |
return target[prop] | |
? target[prop](...args) | |
: target._data[prop](...args); | |
}; | |
} | |
}, | |
set() { | |
throw new Error('Tuple is immutable'); | |
} | |
}); | |
} | |
}; | |
class Tuple { | |
constructor(...values) { | |
this._data = new Array(...values); | |
} | |
valueOf() { | |
return [...this._data]; | |
} | |
toString() { | |
return `(${this._data.join()})`; | |
} | |
} | |
return new Proxy(Tuple, handler); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment