scontainers
Version:
A container/collection/iterator library for JavaScript, comfortable to use, performant and versatile.
140 lines (104 loc) • 2.89 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,
VIt,
Done
} = require('../utils.js');
_testTraitSet(traits.utils);
_testTraitSet(traits.scontainers);
_testTraitSet(traits.semantics);
const _kvIterator = _getSymbol("kvIterator", traits.utils, traits.scontainers, traits.semantics);
const _describeScontainer = _getSymbol("describeScontainer", traits.utils, traits.scontainers, traits.semantics);
const _implTraits = _getSymbol("implTraits", traits.utils, traits.scontainers, traits.semantics);
const _implCoreGenerators = _getSymbol("implCoreGenerators", traits.utils, traits.scontainers, traits.semantics);
const _implCoreTraits = _getSymbol("implCoreTraits", traits.utils, traits.scontainers, traits.semantics);
module.exports = function (ParentCollection) {
if (!ParentCollection.prototype[_kvIterator]) {
return;
}
return function () {
class Values {
static get name() {
return `${ParentCollection.name}::Values`;
}
constructor(coll) {
this.wrapped = coll;
}
toString() {
return `${this.wrapped}.values()`;
}
}
Values.Iterator = class {
constructor(it) {
this.it = it;
}
next() {
const next = this.it.next();
if (!next) {
return new Done();
}
const {
value
} = next;
return new VIt(value);
}
};
Values[_describeScontainer]({
InnerCollection: ParentCollection,
innerCollectionKey: id`wrapped`,
argKeys: [],
mappingOnly: true
});
traits.scontainers[_implTraits](Values.prototype, {
iterator() {
return new Values.Iterator(this.wrapped[_kvIterator]());
}
});
Values[_implCoreGenerators]({
stage(kvn) {
return kvn;
},
indexToParentIndex(index) {
return index;
}
});
Values[_implCoreTraits]({
stage(kvn) {
return kvn;
},
indexToParentIndex(index) {
return index;
}
});
return Values;
};
};