Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Created February 22, 2023 12:30
Show Gist options
  • Save ValentaTomas/d6a07d647dff5c96ccce674c530e2f58 to your computer and use it in GitHub Desktop.
Save ValentaTomas/d6a07d647dff5c96ccce674c530e2f58 to your computer and use it in GitHub Desktop.
Find sequences of incremening numbers in a sorted array of integers
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