Skip to content

Instantly share code, notes, and snippets.

@ardeshireshghi
Created June 1, 2020 14:46
Show Gist options
  • Save ardeshireshghi/080d6318eb13f355369030053af387b0 to your computer and use it in GitHub Desktop.
Save ardeshireshghi/080d6318eb13f355369030053af387b0 to your computer and use it in GitHub Desktop.
Tuple data structure JS
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