Created
March 16, 2020 18:29
-
-
Save zeusdeux/129dd10c7950b514f113268ba0cd6f17 to your computer and use it in GitHub Desktop.
Find if a sequence represented by an array of items in some order is in a dataset that is presented as an array as well
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 assertArray(v) { | |
if (!Array.isArray(v)) { | |
throw new TypeError(`Expected ${v} to be an array`) | |
} | |
return true | |
} | |
function hasSequence(data, seq) { | |
assertArray(data) | |
assertArray(seq) | |
if (!data.length && !seq.length) { | |
return true | |
} | |
let i = 0 | |
for (d of data) { | |
const s = seq[i] | |
if (d === s) { | |
i += 1 | |
} | |
if (i === seq.length) { | |
return true | |
} | |
} | |
return false | |
} | |
// examples: | |
// hasSequence(['a','b', 1, 'c', 2, 'd'], ['b', 2]) -> true | |
// hasSequence([],[]) -> true | |
// hasSequence(['a'], []) -> true | |
// hasSequence([], ['a']) -> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment