UNPKG

@bitblit/ratchet-common

Version:

Common tools for general use

92 lines 3.23 kB
import { RequireRatchet } from './require-ratchet.js'; import { MapRatchet } from './map-ratchet.js'; export class ArrayRatchet { static wrapElementsInArray(input) { return input.map((i) => [i]); } static compareTwoArrays(ar1, ar2, fn) { ar1.sort(fn); ar2.sort(fn); let id1 = 0; let id2 = 0; const rval = { matching: [], setOneOnly: [], setTwoOnly: [], }; while (id1 < ar1.length && id2 < ar2.length) { const aVal = ar1[id1]; const pVal = ar2[id2]; const comp = fn(aVal, pVal); if (comp === 0) { rval.matching.push(aVal); id1++; id2++; } else if (comp < 0) { rval.setOneOnly.push(aVal); id1++; } else { rval.setTwoOnly.push(pVal); id2++; } } if (id1 < ar1.length - 1) { rval.setOneOnly = rval.setOneOnly.concat(ar1.slice(id1)); } if (id2 < ar2.length - 1) { rval.setTwoOnly = rval.setTwoOnly.concat(ar2.slice(id2)); } return rval; } static extractSubarrayFromSortedByNumberField(input, fieldDotPath, minInclusive, maxExclusive) { if (!input || input.length === 0) { return input; } let bottomIdx = minInclusive === null ? 0 : ArrayRatchet.findSplit(input, fieldDotPath, minInclusive) || 0; const topIdx = maxExclusive === null ? input.length : ArrayRatchet.findSplit(input, fieldDotPath, maxExclusive); const bottomValue = MapRatchet.findValueDotPath(input[bottomIdx], fieldDotPath); if (bottomIdx === input.length - 1 && bottomValue < minInclusive) { return []; } if (bottomIdx < input.length && bottomIdx < topIdx && bottomValue < minInclusive) { bottomIdx++; } return input.slice(bottomIdx, topIdx + 1); } static findSplit(input, fieldDotPath, target) { RequireRatchet.notNullOrUndefined(input); RequireRatchet.notNullOrUndefined(fieldDotPath); RequireRatchet.notNullOrUndefined(target); if (input.length === 0 || MapRatchet.findValueDotPath(input[0], fieldDotPath) > target) { return null; } let min = 0; let max = input.length; let rval = null; while (rval === null) { const curIdx = Math.floor((min + max) / 2); const curVal = MapRatchet.findValueDotPath(input[curIdx], fieldDotPath); if (min === max || min === max - 1) { rval = min; } else if (curVal <= target) { min = curIdx; } else { max = curIdx; } } return rval; } static shuffleInPlace(array) { if (array?.length) { for (let i = array.length - 1; i >= 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } } } //# sourceMappingURL=array-ratchet.js.map