Skip to content

Instantly share code, notes, and snippets.

@matthewrobb
Last active September 5, 2019 18:20
Show Gist options
  • Save matthewrobb/5d44e26d73f8ea02740721cf84c3c426 to your computer and use it in GitHub Desktop.
Save matthewrobb/5d44e26d73f8ea02740721cf84c3c426 to your computer and use it in GitHub Desktop.
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