Last active
September 3, 2019 14:51
-
-
Save tomhodgins/1cb7dd4e54101d2117b23880561cdd62 to your computer and use it in GitHub Desktop.
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 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) | |
} | |
} |
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
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