Skip to content

Instantly share code, notes, and snippets.

@thomasvrgn
Created April 5, 2021 09:00
Show Gist options
  • Select an option

  • Save thomasvrgn/14e9b8865360b3f191be8d1d91d3bedd to your computer and use it in GitHub Desktop.

Select an option

Save thomasvrgn/14e9b8865360b3f191be8d1d91d3bedd to your computer and use it in GitHub Desktop.
Pattern matcher in JS
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
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