Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active September 3, 2019 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/1cb7dd4e54101d2117b23880561cdd62 to your computer and use it in GitHub Desktop.
Save tomhodgins/1cb7dd4e54101d2117b23880561cdd62 to your computer and use it in GitHub Desktop.
function patternMatcher(
list = [],
patterns = [item => false],
filter = () => true
) {
const trimmed = list.filter(filter)
const firstIndex = trimmed.findIndex(item =>
patterns.every((pattern, index) =>
pattern(
trimmed[trimmed.indexOf(item) + index]
)
)
)
const start = list.indexOf(trimmed[firstIndex])
const end = list.indexOf(trimmed[firstIndex + patterns.length - 1])
return {
start,
end,
match: trimmed.slice(firstIndex, firstIndex + patterns.length),
original: list.slice(start, end + 1)
}
}
console.log(
patternMatcher(
['a', 'b', 'c', 1, 2, 3, 'd', 'e', 'f', 4, 5, 6],
[
item => typeof item === 'string',
item => typeof item === 'number',
item => typeof item === 'number'
],
token => token !== 'e'
)
)
// expected: {start: 2, end: 4, match: ['c', 1, 2], original: ['c', 1, 2]}
console.log(
patternMatcher(
['a', 1, 2, 3, 4, 'b', 2, 'c'],
[
item => typeof item === 'string',
item => typeof item === 'string',
],
item => typeof item !== 'number'
)
)
// expected: {start: 0, end: 5, match: ['a', 'b'], original: ['a', 1, 2, 3, 4, 'b']}
console.log(
patternMatcher(
[5, 10, 15, 30, 35, 40, 20],
[
num => num > 10,
num => num > 10,
],
num => num < 30
)
)
// expected: {start: 2, end: 6, match: [15, 20], original: [15, 30, 35, 40, 20]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment