Skip to content

Instantly share code, notes, and snippets.

@MarketingPip
Created July 5, 2023 22:03
Show Gist options
  • Save MarketingPip/a665a1ae1d09a82e93cfdc86c3754a1b to your computer and use it in GitHub Desktop.
Save MarketingPip/a665a1ae1d09a82e93cfdc86c3754a1b to your computer and use it in GitHub Desktop.
import stringSimilarity from "https://cdn.skypack.dev/string-similarity@4.0.4";
var extractValues = function(str, pattern, options) {
options = options || {};
var delimiters = options.delimiters || ["{", "}"];
var lowercase = options.lowercase;
var whitespace = options.whitespace;
var special_chars_regex = /[\\\^\$\*\+\.\?\(\)]/g;
var token_regex = new RegExp( delimiters[0] + "([^" + delimiters.join("") + "\t\r\n]+)" + delimiters[1], "g");
var tokens = pattern.match(token_regex);
var pattern_regex = new RegExp(pattern.replace(special_chars_regex, "\\$&").replace(token_regex, "(\.+)"));
if (lowercase) {
str = str.toLowerCase();
}
if (whitespace) {
str = str.replace(/\s+/g, function(match) {
var whitespace_str = "";
for (var i = 0; i < whitespace; i++) {
whitespace_str = whitespace_str + match.charAt(0);
}
return whitespace_str;
});
}
var matches = str.match(pattern_regex);
if (!matches) {
return null;
}
// Allow exact string matches to return an empty object instead of null
if (!tokens) {
return (str === pattern) ? {} : null;
}
matches = matches.splice(1);
var output = {};
for (var i=0; i < tokens.length; i++) {
output[tokens[i].replace( new RegExp( delimiters[0] + "|" + delimiters[1], "g"), "")] = matches[i];
}
return output;
};
let units = ["buy {item} from {place}",
"buy {item} from {place} with {extra}",
"buy {item} from {place} with {extra} please",
"buy {item} from {place} with {extra} please and thank you",
"can you buy {item} from {place} with {extra} please and thank you"]
let input = "hey siri buy coffee from tim hortons with sugar please"
let best = stringSimilarity.findBestMatch(
input,
units,
).bestMatch;
var parsedDate = extractValues(input, best.target, { lowercase: true })
console.log(parsedDate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment