@stringsync/vexml
Version:
MusicXML to Vexflow
87 lines (86 loc) • 2.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.zip = exports.uniqueBy = exports.unique = exports.forEachTriple = exports.groupBy = exports.sortBy = exports.last = exports.first = void 0;
/** Returns the first element of an array or null if it doesn't exist. */
const first = (array) => array[0] ?? null;
exports.first = first;
/** Returns the last element of an array or null if it doesn't exist. */
const last = (array) => array[array.length - 1] ?? null;
exports.last = last;
/** Sorts in-place using the transformation of each array item. */
const sortBy = (array, transform) => {
const memo = new Map();
const value = (item) => {
if (!memo.has(item)) {
memo.set(item, transform(item));
}
return memo.get(item);
};
return array.sort((a, b) => {
const valueA = value(a);
const valueB = value(b);
if (valueA > valueB) {
return 1;
}
if (valueA < valueB) {
return -1;
}
return 0;
});
};
exports.sortBy = sortBy;
/** Groups the elements in the array using the transform. */
const groupBy = (array, transform) => {
return array.reduce((memo, item) => {
const key = transform(item);
memo[key] ??= [];
memo[key].push(item);
return memo;
}, {});
};
exports.groupBy = groupBy;
/** Iterates over each [previous, current, next] triple. */
const forEachTriple = (array, callback) => {
for (let index = 0; index < array.length; index++) {
const previous = array[index - 1] ?? null;
const current = array[index];
const next = array[index + 1] ?? null;
callback([previous, current, next], { index, isFirst: index === 0, isLast: index === array.length - 1 });
}
};
exports.forEachTriple = forEachTriple;
/** Returns a new array with unique elements, preserving the order. */
const unique = (array) => {
const seen = new Set();
return array.filter((item) => {
if (seen.has(item)) {
return false;
}
seen.add(item);
return true;
});
};
exports.unique = unique;
/** Returns a new array with unique elements based on the transformation, preserving the order. */
const uniqueBy = (array, transform) => {
const seen = new Set();
return array.filter((item) => {
const key = transform(item);
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
};
exports.uniqueBy = uniqueBy;
/** Combines two arrays into an array of tuples. */
const zip = (array1, array2) => {
const length = Math.min(array1.length, array2.length);
const result = [];
for (let i = 0; i < length; i++) {
result.push([array1[i], array2[i]]);
}
return result;
};
exports.zip = zip;