Skip to content

Instantly share code, notes, and snippets.

@petsel
Created February 21, 2021 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petsel/d28892fae4c7594daed97c95293bf6a0 to your computer and use it in GitHub Desktop.
Save petsel/d28892fae4c7594daed97c95293bf6a0 to your computer and use it in GitHub Desktop.
/*
* see: [https://stackoverflow.com/questions/66303388/how-to-most-efficiently-splice-an-array-while-looping-through-a-list-of-indices/66304184#66304184]
*
* StackOverflow :: How to most efficiently splice an array
* while looping through a list of indices
* of to be removed array items?
*/
function createRemoveScheme(indexList, targetList) {
return Array
.from(indexList)
.sort((a, b) => a - b)
.reduce((schema, currentPos, idx, referenceList) => {
const { rangeList } = schema;
let range;
const recentPos = referenceList[idx - 1] ?? null;
const nextPos = referenceList[idx + 1] ?? null;
const isOpenNewRange = (
(recentPos === null) ||
(currentPos - recentPos !== 1)
);
const isTerminateRange = (recentPos !== null) && (
(nextPos === null) ||
(nextPos - currentPos !== 1)
);
if (isOpenNewRange) {
range = [ currentPos ];
rangeList.push(range);
}
if (isTerminateRange) {
range = rangeList[rangeList.length - 1];
range.push(currentPos);
}
return schema;
}, { target: targetList, rangeList: [] });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment