Created
February 3, 2017 22:49
-
-
Save akameco/4194ad3714aeefe22a83bf0bff9aec1a to your computer and use it in GitHub Desktop.
クラスとイテレラブル
This file contains 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
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