scontainers
Version:
A container/collection/iterator library for JavaScript, comfortable to use, performant and versatile.
132 lines (101 loc) • 3.09 kB
JavaScript
;
function _implSymbol(target, sym, value) {
Object.defineProperty(target, sym, {
value,
configurable: true
});
return target[sym];
}
function _getSymbol(targetSymName, ...traitSets) {
let symbol;
traitSets.forEach(traitSet => {
const sym = traitSet[targetSymName];
if (typeof sym === 'symbol') {
if (!!symbol && symbol !== sym) {
throw new Error(`Symbol ${targetSymName} offered by multiple trait sets.`);
}
symbol = sym;
}
});
if (!symbol) {
throw new Error(`No trait set is providing symbol ${targetSymName}.`);
}
return symbol;
}
function _testTraitSet(traitSet) {
if (!traitSet || typeof traitSet === 'boolean' || typeof traitSet === 'number' || typeof traitSet === 'string') {
throw new Error(`${traitSet} cannot be used as a trait set.`);
}
}
const {
traits,
id
} = require('../utils.js');
_testTraitSet(traits.utils);
_testTraitSet(traits.scontainers);
_testTraitSet(traits.semantics);
const _describeScontainer = _getSymbol("describeScontainer", traits.utils, traits.scontainers, traits.semantics);
const _implCoreTraits = _getSymbol("implCoreTraits", traits.utils, traits.scontainers, traits.semantics);
const _kvIterator = _getSymbol("kvIterator", traits.utils, traits.scontainers, traits.semantics);
const _reverse = _getSymbol("reverse", traits.utils, traits.scontainers, traits.semantics);
const _skipWhile = _getSymbol("skipWhile", traits.utils, traits.scontainers, traits.semantics);
module.exports = function (ParentCollection) {
const parentProto = ParentCollection.prototype;
return function () {
class SkipWhile {
static get name() {
return `${ParentCollection.name}::SkipWhile`;
}
constructor(coll, fn) {
this.wrapped = coll;
this.fn = fn;
}
toString() {
return `${this.wrapped}.skipWhile(${this.fn.name || 'ƒ'})`;
}
}
SkipWhile[_describeScontainer]({
InnerCollection: ParentCollection,
innerCollectionKey: id`wrapped`,
argKeys: [id`fn`]
});
SkipWhile[_implCoreTraits]({
kvIterator() {
return function kvIterator() {
return {
collection: this.wrapped,
fn: this.fn,
it: this.wrapped[_kvIterator](),
next() {
for (;;) {
const next = this.it.next();
if (!next) {
return;
}
const {
key,
value,
n
} = next;
if (!this.fn(value, key, n)) {
this.next = function next() {
return this.it.next();
};
return next;
}
}
}
};
};
},
reverse() {
if (parentProto[_reverse]) {
return function reverse() {
return this.wrapped[_reverse]()[_skipWhile](this.fn);
};
}
}
});
return SkipWhile;
};
};