Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
consumable-array.mjs
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;
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;
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