Skip to content

Instantly share code, notes, and snippets.

@entrptaher
Forked from arsho/array_splice.js
Last active July 17, 2017 06:08
Show Gist options
  • Save entrptaher/3cb24d85d20fe15e91028c940264897d to your computer and use it in GitHub Desktop.
Save entrptaher/3cb24d85d20fe15e91028c940264897d to your computer and use it in GitHub Desktop.
Array splice implementation to convert an existing array to target array
(() => {
/**
* Fill gaps of an array
* @param {Object} sourceArray - The source array to compare to
* @param {Object} targetArray - The target array to fill the gap
* @param {string} Filler - The element to be used to fill the gap
*/
let similarFill = ((sourceArray, targetArray, filler) => {
let pos = 0;
for (let i = 0; i < targetArray.length; i++) {
// if position is greater or equal of the source array length, then set position as 0
if (pos >= sourceArray.length) {
pos = 0;
}
// if target element is not same as source element, then insert the filler element at that point
if (targetArray[i] != sourceArray[pos]) {
targetArray.splice(i, 0, filler);
}
// increase position along with the loop
pos += 1;
}
return targetArray;
})
// Example Usage
let sourceElem = [1, 2, 3, 4, 5, 6];
let targetElem = [
1, 2, 3, 4, 5, 6,
1, 2, 3, 4, 5, 6,
2, 3, 4, 5, 6,
1, 3, 4, 5, 6,
1, 4, 5, 6
];
let resultElem = [
1, 2, 3, 4, 5, 6,
1, 2, 3, 4, 5, 6,
0, 2, 3, 4, 5, 6,
1, 0, 3, 4, 5, 6,
1, 0, 0, 4, 5, 6
];
// verify our function
// check if array is identical https://stackoverflow.com/a/4025958
function arraysEqual(arr1, arr2) {
if (arr1.length !== arr2.length)
return false;
for (var i = arr1.length; i--;) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
console.log(arraysEqual(similarFill(sourceElem, targetElem, 0), resultElem))
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment