pinafore/src/routes/_utils/arrays.js

47 lines
1.1 KiB
JavaScript
Raw Normal View History

// Merge two arrays, using the given comparator
export function mergeArrays (leftArray, rightArray, comparator) {
2018-01-28 15:02:02 -08:00
let leftIndex = 0
let rightIndex = 0
2019-08-03 13:49:37 -07:00
const merged = []
2018-01-28 15:02:02 -08:00
while (leftIndex < leftArray.length || rightIndex < rightArray.length) {
if (leftIndex === leftArray.length) {
merged.push(rightArray[rightIndex])
rightIndex++
continue
}
if (rightIndex === rightArray.length) {
merged.push(leftArray[leftIndex])
leftIndex++
continue
}
2019-08-03 13:49:37 -07:00
const left = leftArray[leftIndex]
const right = rightArray[rightIndex]
const comparison = comparator(right, left)
if (comparison === 0) {
2018-01-28 15:44:33 -08:00
merged.push(left)
2018-01-28 15:02:02 -08:00
rightIndex++
leftIndex++
} else if (comparison > 0) {
2018-01-28 15:02:02 -08:00
merged.push(right)
rightIndex++
} else {
merged.push(left)
leftIndex++
}
}
return merged
2018-02-08 22:29:29 -08:00
}
export function concat () {
let res = []
for (let i = 0, len = arguments.length; i < len; i++) {
2019-08-03 13:49:37 -07:00
const arg = arguments[i]
if (Array.isArray(arg)) {
res = res.concat(arguments[i])
} else {
res.push(arguments[i])
}
}
return res
}