Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active July 27, 2016 13:59
Show Gist options
  • Save vlad-bezden/33dc1d993242d0a966be3e20aae67a6d to your computer and use it in GitHub Desktop.
Save vlad-bezden/33dc1d993242d0a966be3e20aae67a6d to your computer and use it in GitHub Desktop.
Tuple
'use strict'
class Tuple {
constructor(...args) {
this._args = args
args.forEach((val, index) => {
Object.defineProperty(this, `item${index}`, {
get: () => val
})
})
}
*[Symbol.iterator](){
for (const arg of this._args) {
yield arg
}
}
}
// Usage examples
const t = new Tuple('abc', 123)
const {
item0: a,
item1: b
} = t
console.log(`a: ${a}, b: ${b}`)
// --------------------------
for (const value of t){
console.log(value)
}
// -------------------------
const [first, second] = t
console.log(`first: ${first}, second: ${second}`)

Tuple

JavaScript doesn't have Tuple data type. This example provides custom implementation of Tuple

A Pen by Vlad Bezden

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment