Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Last active June 12, 2018 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save friendlyanon/106ba9fd60db899cf377b33c97eae0e2 to your computer and use it in GitHub Desktop.
Save friendlyanon/106ba9fd60db899cf377b33c97eae0e2 to your computer and use it in GitHub Desktop.
"use strict";
const boxes = new WeakMap;
function Boxes() {
if (!new.target) {
return new Boxes;
}
boxes.set(Object.freeze(this), Object.seal({
list: []
}));
}
function add(id, amount) {
boxes.get(this).list.push(Number(id), Number(amount));
}
function clear() {
boxes.get(this).list = [];
}
function* entries() {
const list = boxes.get(this).list;
let i = -1;
while(++i < list.length /* volatile */) yield [list[i], list[++i]];
}
function length() {
return boxes.get(this).list.length >>> 1;
}
Boxes.prototype = Object.freeze(
Object.defineProperty({
add,
clear,
entries,
[Symbol.iterator]: entries,
constructor: Boxes
}, "length", {
get: length
})
);
module.exports = Boxes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment