Created
April 5, 2021 09:00
-
-
Save thomasvrgn/14e9b8865360b3f191be8d1d91d3bedd to your computer and use it in GitHub Desktop.
Pattern matcher in JS
This file contains hidden or 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(match( | |
| [{ variable: 'x' }, 'test', ['_', 'coucou']], | |
| ['test', 'test', ['bruggh', 'coucou']] | |
| )); // true | |
| console.log(scope); // [ { name: 'x', value: 'test' } ] | |
| console.log(match( | |
| [{ variable: 'x' }, 'test', ['_', 'coucou']], | |
| ['test', 'test', ['bruggh', 'coucou']] | |
| )); | |
| console.log(match( | |
| [{ variable: 'x' }, 'test', ['_', 'coucou'], '_'], | |
| ['test', 'test', ['bruggh', 'coucou']] | |
| )); // false | |
| console.log(match( | |
| [{ variable: 'x' }, 'test', ['_', 'coucou', ['test']]], | |
| ['test', 'test', ['bruggh', 'coucou']] | |
| )); // false |
This file contains hidden or 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
| const scope = []; | |
| function match(patterns, variables) { | |
| let isMatching = false; | |
| for (const index in patterns) { | |
| if (!variables[index]) { | |
| isMatching = false; | |
| break; | |
| } | |
| const pattern = patterns[index]; | |
| const variable = variables[index]; | |
| if (isMatcher(pattern)) { | |
| scope.push({ name: pattern.variable, value: variable, }); | |
| } else if (Array.isArray(pattern)) { | |
| isMatching = match(pattern, variable); | |
| } else if (pattern === '_') { | |
| continue; | |
| } else { | |
| if (variable === pattern) isMatching = true; | |
| else break; | |
| } | |
| } | |
| return isMatching; | |
| } | |
| const isMatcher = (obj) => typeof obj === 'object' && 'variable' in obj; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment