Skip to content

Instantly share code, notes, and snippets.

@blasten
Last active October 30, 2018 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blasten/d0a93c68a2ad4ced2089a96897f84a18 to your computer and use it in GitHub Desktop.
Save blasten/d0a93c68a2ad4ced2089a96897f84a18 to your computer and use it in GitHub Desktop.
function parse(pattern, query) {
const patternWords = pattern.split(' ');
const queryWords = query.split(' ');
const sol = {};
if (!match(patternWords, 0, queryWords, 0, sol)) {
return null;
}
return sol;
}
function isParameterPattern(word) {
return Boolean(word.charAt(0) == '$');
}
function isParameterName(word) {
return word.substr(1);
}
const NUMBER_TEST = /^[0-9]+$/;
function isValidValue(paramName, value) {
if (paramName == 'Number') {
return NUMBER_TEST.test(value);
}
return value != '';
}
function match(patternWords, i, queryWords, j, sol) {
if (i >= patternWords.length && j >= queryWords.length) {
return true;
}
if (i >= patternWords.length || j >= queryWords.length) {
return false;
}
if (isParameterPattern(patternWords[i])) {
const paramName = isParameterName(patternWords[i]);
const currParamValue = sol[paramName] || '';
const newValue = currParamValue + queryWords[j];
if (isValidValue(paramName, newValue)) {
sol[paramName] = newValue;
if (
match(patternWords, i, queryWords, j + 1, sol) ||
match(patternWords, i + 1, queryWords, j + 1, sol)
) {
return true;
}
sol[paramName] = currParamValue;
} else {
sol[paramName] = newValue;
if (match(patternWords, i, queryWords, j + 1, sol)) {
return true;
}
sol[paramName] = currParamValue;
}
} else {
if (patternWords[i] === queryWords[j]) {
if (match(patternWords, i + 1, queryWords, j + 1, sol)) {
return true;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment