typed-utilities
Version:
Strongly typed general purpose utilities
61 lines (42 loc) • 1.61 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.intersection = exports.exactlyOneOrNone = exports.exactlyOne = exports.exactlyNone = exports.deduplicate = exports.containEqualItems = void 0;
const strictEquals = (a, b) => a === b;
const containEqualItems = (t1, t2, equals = strictEquals) => t1.length === t2.length && t1.every(aItem => t2.some(bItem => equals(aItem, bItem)));
exports.containEqualItems = containEqualItems;
const deduplicate = (t, equals = strictEquals) => t.reduce((t, item) => {
if (!t.find(existingItem => equals(existingItem, item))) {
return [...t, item];
}
return t;
}, []);
exports.deduplicate = deduplicate;
const intersection = (arrays, equals = strictEquals) => arrays.length === 0 ? [] : deduplicate(arrays.slice(1).reduce((t, intersection) => intersection.filter(item => t.some(existingItem => equals(item, existingItem))), arrays[0]), equals);
exports.intersection = intersection;
const exactlyNone = t => {
if (t.length !== 0) {
throw new Error(`expected exactly 0 items, received ${t.length}`);
}
return null;
};
exports.exactlyNone = exactlyNone;
const exactlyOne = t => {
if (t.length !== 1) {
throw new Error(`expected exactly 1 item, received ${t.length}`);
}
return t[0];
};
exports.exactlyOne = exactlyOne;
const exactlyOneOrNone = t => {
if (t.length === 0) {
return null;
}
if (t.length === 1) {
return t[0];
}
throw new Error(`expected exactly 0 or 1 item, received ${t.length}`);
};
exports.exactlyOneOrNone = exactlyOneOrNone;
//# sourceMappingURL=Array.js.map