UNPKG

@stringsync/vexml

Version:

MusicXML to Vexflow

76 lines (75 loc) 2.47 kB
/** Returns the first element of an array or null if it doesn't exist. */ export const first = (array) => array[0] ?? null; /** Returns the last element of an array or null if it doesn't exist. */ export const last = (array) => array[array.length - 1] ?? null; /** Sorts in-place using the transformation of each array item. */ export 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; }); }; /** Groups the elements in the array using the transform. */ export const groupBy = (array, transform) => { return array.reduce((memo, item) => { const key = transform(item); memo[key] ??= []; memo[key].push(item); return memo; }, {}); }; /** Iterates over each [previous, current, next] triple. */ export 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 }); } }; /** Returns a new array with unique elements, preserving the order. */ export const unique = (array) => { const seen = new Set(); return array.filter((item) => { if (seen.has(item)) { return false; } seen.add(item); return true; }); }; /** Returns a new array with unique elements based on the transformation, preserving the order. */ export 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; }); }; /** Combines two arrays into an array of tuples. */ export 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; };