@studyportals/sp-hs-misc
Version:
Miscellaneous code used in HouseStark's projects
79 lines • 2.63 kB
JavaScript
class ArrayHelper {
first(input) {
if (0 === input.length) {
throw new Error("Could not extract the first item of an empty array");
}
return input[0];
}
firstOrDefault(input, defaultValueFactoryFn) {
if (0 === input.length) {
return defaultValueFactoryFn();
}
return input[0];
}
last(input) {
if (0 === input.length) {
throw new Error("Could not extract the last item of an empty array");
}
return input[input.length - 1];
}
lastOrDefault(input, defaultValueFactoryFn) {
if (0 === input.length) {
return defaultValueFactoryFn();
}
return input[input.length - 1];
}
toSet(input) {
return new Set(input);
}
mapFirst(input, mapperFn) {
return mapperFn(this.first(input));
}
minimum(input) {
return input.reduce((left, right) => left < right ? left : right);
}
maximum(input) {
return input.reduce((left, right) => left > right ? left : right);
}
extractMinimum(input, extractorFn) {
return this.minimum(input.map(_ => extractorFn(_)));
}
extractMaximum(input, extractorFn) {
return this.maximum(input.map(_ => extractorFn(_)));
}
equivalent(input, other, toPrimitiveFn) {
const inputItemToOccurances = this.countMembers(input, toPrimitiveFn);
const otherItemToOccurances = this.countMembers(other, toPrimitiveFn);
for (const item of input) {
const key = toPrimitiveFn ? toPrimitiveFn(item) : item;
if (inputItemToOccurances.get(key) !== otherItemToOccurances.get(key)) {
return false;
}
}
return input.length === other.length;
}
removeDuplicates(input, toPrimitiveFn) {
const map = new Map();
for (const item of input) {
const primitive = toPrimitiveFn ? toPrimitiveFn(item) : item;
map.set(primitive, item);
}
return Array.from(map.values());
}
countMembers(input, toPrimitiveFn) {
const itemToOccurances = new Map();
for (const item of input) {
const key = toPrimitiveFn ? toPrimitiveFn(item) : item;
const occurances = itemToOccurances.get(key);
if (occurances) {
itemToOccurances.set(key, occurances + 1);
}
else {
itemToOccurances.set(key, 1);
}
}
return itemToOccurances;
}
}
export { ArrayHelper };
//# sourceMappingURL=array-helper.class.js.map