scontainers
Version:
A container/collection/iterator library for JavaScript, comfortable to use, performant and versatile.
102 lines (76 loc) • 2.18 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 _nth = _getSymbol("nth", traits.utils, traits.scontainers, traits.semantics);
const _describeScontainer = _getSymbol("describeScontainer", traits.utils, traits.scontainers, traits.semantics);
const _implCoreTraits = _getSymbol("implCoreTraits", traits.utils, traits.scontainers, traits.semantics);
const _len = _getSymbol("len", traits.utils, traits.scontainers, traits.semantics);
module.exports = function (ParentCollection) {
if (!ParentCollection.prototype[_nth]) {
return;
}
return function () {
class Reverse {
static get name() {
return `${ParentCollection.name}::Reverse`;
}
constructor(coll) {
this.wrapped = coll;
}
toString() {
return `${this.wrapped}.reverse()`;
}
}
Reverse[_describeScontainer]({
InnerCollection: ParentCollection,
innerCollectionKey: id`wrapped`,
argKeys: [],
mappingOnly: true
});
Reverse[_implCoreTraits]({
nStage(kvn) {
return kvn;
},
nToParentN(n) {
return this[_len]() - n - 1;
},
reverse() {
return this.wrapped;
}
});
return Reverse;
};
};