Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Created March 16, 2020 18:29
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 zeusdeux/129dd10c7950b514f113268ba0cd6f17 to your computer and use it in GitHub Desktop.
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
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