aboutsummaryrefslogtreecommitdiff
path: root/fuzzel.lua
diff options
context:
space:
mode:
authorAlexander Pickering <alexandermpickering@gmail.com>2016-06-05 20:58:42 -0400
committerAlexander Pickering <alexandermpickering@gmail.com>2016-06-05 20:58:42 -0400
commit1c70e2dcaebe1bb18ec7d28f2caf2495efd5717d (patch)
tree3c878d4a01ad790c74711fc69b2ca31abd3c167e /fuzzel.lua
parentcb25042bdab297fd51319cc5a3b3f986b07f3da1 (diff)
downloadfuzzel-1c70e2dcaebe1bb18ec7d28f2caf2495efd5717d.tar.gz
fuzzel-1c70e2dcaebe1bb18ec7d28f2caf2495efd5717d.tar.bz2
fuzzel-1c70e2dcaebe1bb18ec7d28f2caf2495efd5717d.zip
Fixed a bug in hamming distance, and improved comments
Diffstat (limited to 'fuzzel.lua')
-rw-r--r--fuzzel.lua16
1 files changed, 14 insertions, 2 deletions
diff --git a/fuzzel.lua b/fuzzel.lua
index f86de5c..f3432dc 100644
--- a/fuzzel.lua
+++ b/fuzzel.lua
@@ -1,7 +1,7 @@
--[[
Fuzzel v1.0 - Alexander "Apickx" Pickering
Entered into the public domain June 2, 2016
- You are not required to, but consider linking back to the source!
+ You are not required to, but consider putting a link to the source in your file's comments!
Some helper functions for calculateing distance between two strings
@@ -97,6 +97,8 @@
fuzzel.fsd = fuzzel.FuzzySortDistance
fuzzel.fsr = fuzzel.FuzzySortRatio
]]
+
+--Assign locals to these to the minifier can compress the file better
local strlen,chrat,min,asrt,prs,iprs,typ,upack,tblins,tblsrt = string.len,string.byte,math.min,assert,pairs,ipairs,type,unpack,table.insert,table.sort
local fuzzel = {}
@@ -178,7 +180,7 @@ function fuzzel.HammingDistance(stringa,stringb)
asrt(len == strlen(stringb),"Hamming Distance cannot be calculated on two strings of different lengths:\"" .. stringa .. "\" \"" .. stringb .. "\"")
local dist = 0
for i = 1,len do
- dist = dist + (chrat(stringa,i) ~= chrat(stringb,i) and 1)
+ dist = dist + ((chrat(stringa,i) ~= chrat(stringb,i)) and 1 or 0)
end
return dist
end
@@ -190,7 +192,10 @@ end
fuzzel.hr = fuzzel.HammingRatio
local function FuzzySearch(str,func,...)
+ --Allow varargs, or a table
local looparg = typ(arg[1]) == "table" and arg[1] or arg
+
+ --Find the string with the shortest distance to the string we were supplied
local tmin = func(looparg[1],str)
local sout = looparg[1]
for k,v in prs(looparg) do
@@ -213,18 +218,25 @@ function fuzzel.FuzzyFindRatio(str,...)
end
local function FuzzySort(str, func, ...)
+ --allow varargs, or a table
local looparg = typ(arg[1]) == "table" and arg[1] or arg
+
+ --Roughly sort everything by it's distance to the string
local usorted = {}
for k,v in prs(looparg) do
local dist = func(str,v)
usorted[dist] = usorted[dist] or {}
tblins(usorted[dist],v)
end
+
+ --Actually sort them into something can can be iterated with ipairs
local sorted = {}
for k,v in prs(usorted) do
tblins(sorted,k)
end
tblsrt(sorted)
+
+ --Then build our output table
local otbl = {}
for k,v in prs(sorted) do
for i,j in prs(usorted[v]) do