closest-str
closest-str is a library for finding closest key in the dictionary and getting it's value.
Installation
Install a lib using npm
npm i closest-str
Usage
Basic usage:
var closest = require("closest-str");
closest.setdict({
"hello": function(query) {
return "Hello! You typed: " + query
},
"goodbye": function() {
return "Goodbye!";
}
});
closest.setdict([
{
query: "hello",
answer: function(query) {
return "Hello! You typed: " + query
}
}
]);
function makeRequest(query) {
return closest.request(query).answer(query);
}
makeRequest("hello, random guy!");
makeRequest("goodbye then");
Load dict from file
closest.setdict("./dict.json");
You can detect, if all matches are too low:
closest.setlow(0.4);
closest.setlow("No matching keys");
closest.request("This is a random string, no close key in dictionary");
We can optimize our code... We don't need to check other keys if there was exact match.
closest.setmax(1);
Also we can provide custom params for separate queries.
closest.request("hello", {
low: 0.5,
lowresponse: "I don't understand you",
max: 0.9,
skip: 5
});
What can it be used for?
Simple bots:
closest.setdict({
"weather": function(query, callback) {
callback();
}
});
closest.setlow(0.3);
closest.setlow(function(query, callback) {
callback("I don't understand you");
});
function makeRequest(query, callback) {
closest.request(query).answer(callback);
}
makeRequest("what's the weather", console.log);
Word correction:
closest.setdict({
"pen": "pen",
"apple": "apple",
"pineapple": "pineapple"
});
closest.setlow(0.4);
closest.setlow("No idea");
closest.request("aple").answer;
closest.request("pnapple").answer;
Chat bot... why not?
var fs = require("fs");
var closest = require("closest-str");
var answers = fs.readFileSync("./answers.txt").split("\n");
var dict = {};
answers.forEach(function(ans) {
var s = ans.split("\\");
if (dict[s[0]]) dict[s[0]].push(s[1]);
else dict[s[0]] = [dict[s[1]]];
});
closest.setdict(dict);
function randPick(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function makeRequest(query) {
return randPick(closest.request(query).answer);
}
Other
For comparing two strings
closest._similarity("test", "tost");
closest._similarity("test", "TEST");
closest.__dict;
closest.__low;
closest.__lowresponse;
closest.__max;
Changelog
- 2.2.0
- Load dict from file
- 2.1.0
- Added custom params for separate queries
- Added max similarity
- Dict can be array
- 2.0.0
- Initial release
TODO
- Async requests (for big dictionaries)