Last active
September 5, 2019 18:20
-
-
Save matthewrobb/5d44e26d73f8ea02740721cf84c3c426 to your computer and use it in GitHub Desktop.
consumable-array.mjs
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
const { | |
defineProperties, | |
getOwnPropertyDescriptors | |
} = Object; | |
/** | |
* A root Array-like "class" compatible with both es5 and es6 styles | |
*/ | |
export function ArrayLike() { | |
if (!(this instanceof ArrayLike)) { | |
// "callable-constructor" why not? | |
return new ArrayLike(...arguments); | |
} | |
Array.apply(this, arguments); | |
} | |
defineProperties( | |
ArrayLike.prototype, | |
getOwnPropertyDescriptors(Array.prototype) | |
); | |
export default ArrayLike; |
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
import ArrayLike from "./array-like.mjs"; | |
/** | |
* Basic idea: iteration is consumption | |
*/ | |
export class ConsumableArray extends ArrayLike { | |
[Symbol.iterator]() { | |
return this; | |
} | |
next() { | |
return this; | |
} | |
get value() { | |
return this.shift(); | |
} | |
get done() { | |
return !this.length; | |
} | |
} | |
export default ConsumableArray; |
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
import ConsumableArray from "./consumable-array.mjs"; | |
/** | |
* Demonstration: Will maintain a list of 10 items | |
*/ | |
export class SelfPopulatingList extends ConsumableArray { | |
constructor() { | |
super(...arguments); | |
let count = 0; | |
const tick = ()=> { | |
if (this.length < 10) { | |
this.push({ id: count++ }); | |
} | |
setTimeout(tick, 1000); | |
}; | |
setTimeout(tick); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment