Created
February 21, 2021 18:17
-
-
Save petsel/d28892fae4c7594daed97c95293bf6a0 to your computer and use it in GitHub Desktop.
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
/* | |
* 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