pinafore/routes/_utils/arrays.js

47 lines
1.1 KiB
JavaScript
Raw Normal View History

2018-01-29 00:02:02 +01:00
// Merge two arrays, assuming both input arrays have the same order
// and items are comparable
2018-02-09 07:29:29 +01:00
export function mergeArrays (leftArray, rightArray) {
2018-01-29 00:02:02 +01:00
let leftIndex = 0
let rightIndex = 0
let merged = []
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
}
let left = leftArray[leftIndex]
let right = rightArray[rightIndex]
if (right === left) {
2018-01-29 00:44:33 +01:00
merged.push(left)
2018-01-29 00:02:02 +01:00
rightIndex++
leftIndex++
} else if (parseInt(right, 10) > parseInt(left, 10)) {
merged.push(right)
rightIndex++
} else {
merged.push(left)
leftIndex++
}
}
return merged
2018-02-09 07:29:29 +01:00
}
export function concat () {
let res = []
for (let i = 0, len = arguments.length; i < len; i++) {
let arg = arguments[i]
if (Array.isArray(arg)) {
res = res.concat(arguments[i])
} else {
res.push(arguments[i])
}
}
return res
}