Created
February 22, 2023 12:30
-
-
Save ValentaTomas/d6a07d647dff5c96ccce674c530e2f58 to your computer and use it in GitHub Desktop.
Find sequences of incremening numbers in a sorted array of integers
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
function getLast<T>(items: T[]) { | |
if (items.length > 0) { | |
return items[items.length - 1] | |
} | |
} | |
/** | |
* @param items Sorted array of integers | |
*/ | |
export function findSequences(items: number[]) { | |
return items.reduce<number[][]>((seq, item) => { | |
const lastSequence = getLast(seq) | |
const lastItem = lastSequence ? getLast(lastSequence) : undefined | |
if (lastItem === item - 1) { | |
lastSequence?.push(item) | |
} else { | |
seq.push([item]) | |
} | |
return seq | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment