scontainers
Version:
A container/collection/iterator library for JavaScript, comfortable to use, performant and versatile.
111 lines (84 loc) • 2.46 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 _implCoreGenerators = _getSymbol("implCoreGenerators", traits.utils, traits.scontainers, traits.semantics);
const _call = _getSymbol("call", traits.utils, traits.scontainers, traits.semantics);
const _implCoreTraits = _getSymbol("implCoreTraits", traits.utils, traits.scontainers, traits.semantics);
module.exports = function (ParentCollection) {
return function () {
class Map {
static get name() {
return `${ParentCollection.name}::Map`;
}
constructor(coll, mapFn) {
this.wrapped = coll;
this.mapFn = mapFn;
}
toString() {
return `${this.wrapped}.map(${this.mapFn.name || 'ƒ'})`;
}
}
Map[_describeScontainer]({
InnerCollection: ParentCollection,
innerCollectionKey: id`wrapped`,
argKeys: [id`mapFn`],
mappingOnly: true
});
Map[_implCoreGenerators]({
stage(kvn) {
const {
mapFn
} = this.args;
kvn.value = mapFn[_call](kvn.value, kvn.key, kvn.n);
return kvn;
},
indexToParentIndex(index) {
return index;
}
});
Map[_implCoreTraits]({
stage(kvn) {
kvn.value = this.mapFn(kvn.value, kvn.key, kvn.n);
return kvn;
},
indexToParentIndex(index) {
return index;
}
});
return Map;
};
};