Last active
October 30, 2018 17:03
-
-
Save blasten/d0a93c68a2ad4ced2089a96897f84a18 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 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