UNPKG

scontainers

Version:

A container/collection/iterator library for JavaScript, comfortable to use, performant and versatile.

115 lines (88 loc) 2.85 kB
"use strict"; 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, ReorderedIterator, options } = require('../utils.js'); _testTraitSet(traits.utils); _testTraitSet(traits.scontainers); _testTraitSet(traits.semantics); const _kvIterator = _getSymbol("kvIterator", traits.utils, traits.scontainers, traits.semantics); const _kvReorderedIterator = _getSymbol("kvReorderedIterator", 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); module.exports = function (ParentCollection) { const parentProto = ParentCollection.prototype; // TODO: I guess I should ignore parent's `kvReorderedIterator`, but it's needed by the current `/src/lodashcmp.js` if (!options.debug || !parentProto[_kvIterator] && !parentProto[_kvReorderedIterator]) { return; } return function () { class IterableOnly { static get name() { return `${ParentCollection.name}::IterableOnly`; } constructor(coll) { this.wrapped = coll; } toString() { return `${this.wrapped}.iter()`; } } IterableOnly[_describeScontainer]({ InnerCollection: ParentCollection, innerCollectionKey: id`wrapped`, argKeys: [] }); IterableOnly[_implCoreTraits]({ kvIterator() { if (parentProto[_kvIterator]) { return function () { return this.wrapped[_kvIterator](); }; } }, kvReorderedIterator() { if (IterableOnly.prototype[_kvIterator]) { return function () { return new ReorderedIterator.FromIterator(this[_kvIterator]()); }; } if (parentProto[_kvReorderedIterator]) { return function () { return this.wrapped[_kvReorderedIterator](); }; } } }); return IterableOnly; }; };