Last active
October 16, 2024 01:35
-
-
Save jasonsperske/c70d227126ae597693c76acd74bd364a to your computer and use it in GitHub Desktop.
Array Merge Util (takes an ordered array and creates a new array with the value that overlap included while the values outside are left alone)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const src = [3, 4, 8, 9] | |
/** | |
* @param {number[]} input | |
* @param {number[]} source | |
* @returns | |
*/ | |
function update(input, source) { | |
if (input.length === 0) return [...source] | |
if (source.length === 0) return [...input] | |
let first = input[0] | |
let last = input[input.length - 1] | |
let leading_index = 0 | |
for (; first >= source[leading_index] && leading_index < source.length; leading_index++) { } | |
let trailing_index = source.length - 1 | |
for (; last < source[trailing_index] && trailing_index >= leading_index; trailing_index--) { } | |
return [...source.slice(0, leading_index), ...input, ...source.slice(trailing_index + 1)] | |
} | |
// [3, 4, 8, 9] | |
// [2, 3, 5] | |
console.log(update([2, 3, 5], src)) // [2, 3, 5, 8, 9] | |
// [3, 4, 8, 9] | |
// [2, 3, 5, 10] | |
console.log(update([2, 3, 5, 10], src)) // [2, 3, 5, 10] | |
// [3, 4, 8, 9] | |
// [1, 2] | |
console.log(update([1, 2], src)) // [1, 2, 3, 4, 8, 9] | |
// [3, 4, 8, 9] | |
// [10, 11] | |
console.log(update([10, 11], src)) // [3, 4, 8, 9, 10, 11] | |
// [3, 4, 8, 9] | |
// [5, 6, 7] | |
console.log(update([5, 6, 7], src)) // [3, 4, 5, 6, 7, 8, 9, 10, 11] | |
console.log(update([1, 2, 3], [])) // [1, 2, 3] | |
console.log(update([], [3, 4, 5])) // [3, 4, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment