Skip to content

Instantly share code, notes, and snippets.

@akameco
Created Feb 3, 2017
Embed
What would you like to do?
クラスとイテレラブル
class Store {
constructor() {
this.obj = {}
}
get(key) {
return this.obj[key]
}
set(key, val) {
this.obj[key] = val
}
* [Symbol.iterator]() {
const obj = this.obj
for (const key of Object.keys(obj)) {
yield [key, obj[key]]
}
}
}
const s = new Store()
s.set('a', 1)
const a = s.get('a')
console.log(a) // => 1
s.set('b', 2)
s.set('c', 3)
for (const v of s) {
console.log(v)
}
/* =>
[ 'a', 1 ]
[ 'b', 2 ]
[ 'c', 3 ]
*/
console.log(...s);
// => [ 'a', 1 ] [ 'b', 2 ] [ 'c', 3 ]
const [, b, c] = s
console.log(b, c);
// => [ 'b', 2 ] [ 'c', 3 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment