Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.