fuzzysort.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /*
  2. MIT License
  3. Copyright (c) 2018 Stephen Kamenar
  4. WHAT: SublimeText-like Fuzzy Search
  5. USAGE:
  6. fuzzysort.single('fs', 'Fuzzy Search') // {score: -16}
  7. fuzzysort.single('test', 'test') // {score: 0}
  8. fuzzysort.single('doesnt exist', 'target') // null
  9. fuzzysort.go('mr', ['Monitor.cpp', 'MeshRenderer.cpp'])
  10. // [{score: -18, target: "MeshRenderer.cpp"}, {score: -6009, target: "Monitor.cpp"}]
  11. fuzzysort.highlight(fuzzysort.single('fs', 'Fuzzy Search'), '<b>', '</b>')
  12. // <b>F</b>uzzy <b>S</b>earch
  13. */
  14. // UMD (Universal Module Definition) for fuzzysort
  15. ;(function(root, UMD) {
  16. if(typeof define === 'function' && define.amd) define([], UMD)
  17. else if(typeof module === 'object' && module.exports) module.exports = UMD()
  18. else root.fuzzysort = UMD()
  19. })(this, function UMD() { function fuzzysortNew(instanceOptions) {
  20. var fuzzysort = {
  21. single: function(search, target, options) {
  22. if(!search) return null
  23. if(!isObj(search)) search = fuzzysort.getPreparedSearch(search)
  24. if(!target) return null
  25. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  26. var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo
  27. : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo
  28. : true
  29. var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo
  30. return algorithm(search, target, search[0])
  31. // var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991
  32. // var result = algorithm(search, target, search[0])
  33. // if(result === null) return null
  34. // if(result.score < threshold) return null
  35. // return result
  36. },
  37. go: function(search, targets, options) {
  38. if(!search) return noResults
  39. search = fuzzysort.prepareSearch(search)
  40. var searchLowerCode = search[0]
  41. var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991
  42. var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991
  43. var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo
  44. : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo
  45. : true
  46. var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo
  47. var resultsLen = 0; var limitedCount = 0
  48. var targetsLen = targets.length
  49. // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys]
  50. // options.keys
  51. if(options && options.keys) {
  52. var scoreFn = options.scoreFn || defaultScoreFn
  53. var keys = options.keys
  54. var keysLen = keys.length
  55. for(var i = targetsLen - 1; i >= 0; --i) { var obj = targets[i]
  56. var objResults = new Array(keysLen)
  57. for (var keyI = keysLen - 1; keyI >= 0; --keyI) {
  58. var key = keys[keyI]
  59. var target = getValue(obj, key)
  60. if(!target) { objResults[keyI] = null; continue }
  61. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  62. objResults[keyI] = algorithm(search, target, searchLowerCode)
  63. }
  64. objResults.obj = obj // before scoreFn so scoreFn can use it
  65. var score = scoreFn(objResults)
  66. if(score === null) continue
  67. if(score < threshold) continue
  68. objResults.score = score
  69. if(resultsLen < limit) { q.add(objResults); ++resultsLen }
  70. else {
  71. ++limitedCount
  72. if(score > q.peek().score) q.replaceTop(objResults)
  73. }
  74. }
  75. // options.key
  76. } else if(options && options.key) {
  77. var key = options.key
  78. for(var i = targetsLen - 1; i >= 0; --i) { var obj = targets[i]
  79. var target = getValue(obj, key)
  80. if(!target) continue
  81. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  82. var result = algorithm(search, target, searchLowerCode)
  83. if(result === null) continue
  84. if(result.score < threshold) continue
  85. // have to clone result so duplicate targets from different obj can each reference the correct obj
  86. result = {target:result.target, _targetLowerCodes:null, _nextBeginningIndexes:null, score:result.score, indexes:result.indexes, obj:obj} // hidden
  87. if(resultsLen < limit) { q.add(result); ++resultsLen }
  88. else {
  89. ++limitedCount
  90. if(result.score > q.peek().score) q.replaceTop(result)
  91. }
  92. }
  93. // no keys
  94. } else {
  95. for(var i = targetsLen - 1; i >= 0; --i) { var target = targets[i]
  96. if(!target) continue
  97. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  98. var result = algorithm(search, target, searchLowerCode)
  99. if(result === null) continue
  100. if(result.score < threshold) continue
  101. if(resultsLen < limit) { q.add(result); ++resultsLen }
  102. else {
  103. ++limitedCount
  104. if(result.score > q.peek().score) q.replaceTop(result)
  105. }
  106. }
  107. }
  108. if(resultsLen === 0) return noResults
  109. var results = new Array(resultsLen)
  110. for(var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll()
  111. results.total = resultsLen + limitedCount
  112. return results
  113. },
  114. goAsync: function(search, targets, options) {
  115. var canceled = false
  116. var p = new Promise(function(resolve, reject) {
  117. if(!search) return resolve(noResults)
  118. search = fuzzysort.prepareSearch(search)
  119. var searchLowerCode = search[0]
  120. var q = fastpriorityqueue()
  121. var iCurrent = targets.length - 1
  122. var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991
  123. var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991
  124. var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo
  125. : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo
  126. : true
  127. var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo
  128. var resultsLen = 0; var limitedCount = 0
  129. function step() {
  130. if(canceled) return reject('canceled')
  131. var startMs = Date.now()
  132. // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys]
  133. // options.keys
  134. if(options && options.keys) {
  135. var scoreFn = options.scoreFn || defaultScoreFn
  136. var keys = options.keys
  137. var keysLen = keys.length
  138. for(; iCurrent >= 0; --iCurrent) { var obj = targets[iCurrent]
  139. var objResults = new Array(keysLen)
  140. for (var keyI = keysLen - 1; keyI >= 0; --keyI) {
  141. var key = keys[keyI]
  142. var target = getValue(obj, key)
  143. if(!target) { objResults[keyI] = null; continue }
  144. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  145. objResults[keyI] = algorithm(search, target, searchLowerCode)
  146. }
  147. objResults.obj = obj // before scoreFn so scoreFn can use it
  148. var score = scoreFn(objResults)
  149. if(score === null) continue
  150. if(score < threshold) continue
  151. objResults.score = score
  152. if(resultsLen < limit) { q.add(objResults); ++resultsLen }
  153. else {
  154. ++limitedCount
  155. if(score > q.peek().score) q.replaceTop(objResults)
  156. }
  157. if(iCurrent%1000/*itemsPerCheck*/ === 0) {
  158. if(Date.now() - startMs >= 10/*asyncInterval*/) {
  159. isNode?setImmediate(step):setTimeout(step)
  160. return
  161. }
  162. }
  163. }
  164. // options.key
  165. } else if(options && options.key) {
  166. var key = options.key
  167. for(; iCurrent >= 0; --iCurrent) { var obj = targets[iCurrent]
  168. var target = getValue(obj, key)
  169. if(!target) continue
  170. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  171. var result = algorithm(search, target, searchLowerCode)
  172. if(result === null) continue
  173. if(result.score < threshold) continue
  174. // have to clone result so duplicate targets from different obj can each reference the correct obj
  175. result = {target:result.target, _targetLowerCodes:null, _nextBeginningIndexes:null, score:result.score, indexes:result.indexes, obj:obj} // hidden
  176. if(resultsLen < limit) { q.add(result); ++resultsLen }
  177. else {
  178. ++limitedCount
  179. if(result.score > q.peek().score) q.replaceTop(result)
  180. }
  181. if(iCurrent%1000/*itemsPerCheck*/ === 0) {
  182. if(Date.now() - startMs >= 10/*asyncInterval*/) {
  183. isNode?setImmediate(step):setTimeout(step)
  184. return
  185. }
  186. }
  187. }
  188. // no keys
  189. } else {
  190. for(; iCurrent >= 0; --iCurrent) { var target = targets[iCurrent]
  191. if(!target) continue
  192. if(!isObj(target)) target = fuzzysort.getPrepared(target)
  193. var result = algorithm(search, target, searchLowerCode)
  194. if(result === null) continue
  195. if(result.score < threshold) continue
  196. if(resultsLen < limit) { q.add(result); ++resultsLen }
  197. else {
  198. ++limitedCount
  199. if(result.score > q.peek().score) q.replaceTop(result)
  200. }
  201. if(iCurrent%1000/*itemsPerCheck*/ === 0) {
  202. if(Date.now() - startMs >= 10/*asyncInterval*/) {
  203. isNode?setImmediate(step):setTimeout(step)
  204. return
  205. }
  206. }
  207. }
  208. }
  209. if(resultsLen === 0) return resolve(noResults)
  210. var results = new Array(resultsLen)
  211. for(var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll()
  212. results.total = resultsLen + limitedCount
  213. resolve(results)
  214. }
  215. isNode?setImmediate(step):step()
  216. })
  217. p.cancel = function() { canceled = true }
  218. return p
  219. },
  220. highlight: function(result, hOpen, hClose) {
  221. if(result === null) return null
  222. if(hOpen === undefined) hOpen = '<b>'
  223. if(hClose === undefined) hClose = '</b>'
  224. var highlighted = ''
  225. var matchesIndex = 0
  226. var opened = false
  227. var target = result.target
  228. var targetLen = target.length
  229. var matchesBest = result.indexes
  230. for(var i = 0; i < targetLen; ++i) { var char = target[i]
  231. if(matchesBest[matchesIndex] === i) {
  232. ++matchesIndex
  233. if(!opened) { opened = true
  234. highlighted += hOpen
  235. }
  236. if(matchesIndex === matchesBest.length) {
  237. highlighted += char + hClose + target.substr(i+1)
  238. break
  239. }
  240. } else {
  241. if(opened) { opened = false
  242. highlighted += hClose
  243. }
  244. }
  245. highlighted += char
  246. }
  247. return highlighted
  248. },
  249. prepare: function(target) {
  250. if(!target) return
  251. return {target:target, _targetLowerCodes:fuzzysort.prepareLowerCodes(target), _nextBeginningIndexes:null, score:null, indexes:null, obj:null} // hidden
  252. },
  253. prepareSlow: function(target) {
  254. if(!target) return
  255. return {target:target, _targetLowerCodes:fuzzysort.prepareLowerCodes(target), _nextBeginningIndexes:fuzzysort.prepareNextBeginningIndexes(target), score:null, indexes:null, obj:null} // hidden
  256. },
  257. prepareSearch: function(search) {
  258. if(!search) return
  259. return fuzzysort.prepareLowerCodes(search)
  260. },
  261. // Below this point is only internal code
  262. // Below this point is only internal code
  263. // Below this point is only internal code
  264. // Below this point is only internal code
  265. getPrepared: function(target) {
  266. if(target.length > 999) return fuzzysort.prepare(target) // don't cache huge targets
  267. var targetPrepared = preparedCache.get(target)
  268. if(targetPrepared !== undefined) return targetPrepared
  269. targetPrepared = fuzzysort.prepare(target)
  270. preparedCache.set(target, targetPrepared)
  271. return targetPrepared
  272. },
  273. getPreparedSearch: function(search) {
  274. if(search.length > 999) return fuzzysort.prepareSearch(search) // don't cache huge searches
  275. var searchPrepared = preparedSearchCache.get(search)
  276. if(searchPrepared !== undefined) return searchPrepared
  277. searchPrepared = fuzzysort.prepareSearch(search)
  278. preparedSearchCache.set(search, searchPrepared)
  279. return searchPrepared
  280. },
  281. algorithm: function(searchLowerCodes, prepared, searchLowerCode) {
  282. var targetLowerCodes = prepared._targetLowerCodes
  283. var searchLen = searchLowerCodes.length
  284. var targetLen = targetLowerCodes.length
  285. var searchI = 0 // where we at
  286. var targetI = 0 // where you at
  287. var typoSimpleI = 0
  288. var matchesSimpleLen = 0
  289. // very basic fuzzy match; to remove non-matching targets ASAP!
  290. // walk through target. find sequential matches.
  291. // if all chars aren't found then exit
  292. for(;;) {
  293. var isMatch = searchLowerCode === targetLowerCodes[targetI]
  294. if(isMatch) {
  295. matchesSimple[matchesSimpleLen++] = targetI
  296. ++searchI; if(searchI === searchLen) break
  297. searchLowerCode = searchLowerCodes[typoSimpleI===0?searchI : (typoSimpleI===searchI?searchI+1 : (typoSimpleI===searchI-1?searchI-1 : searchI))]
  298. }
  299. ++targetI; if(targetI >= targetLen) { // Failed to find searchI
  300. // Check for typo or exit
  301. // we go as far as possible before trying to transpose
  302. // then we transpose backwards until we reach the beginning
  303. for(;;) {
  304. if(searchI <= 1) return null // not allowed to transpose first char
  305. if(typoSimpleI === 0) { // we haven't tried to transpose yet
  306. --searchI
  307. var searchLowerCodeNew = searchLowerCodes[searchI]
  308. if(searchLowerCode === searchLowerCodeNew) continue // doesn't make sense to transpose a repeat char
  309. typoSimpleI = searchI
  310. } else {
  311. if(typoSimpleI === 1) return null // reached the end of the line for transposing
  312. --typoSimpleI
  313. searchI = typoSimpleI
  314. searchLowerCode = searchLowerCodes[searchI + 1]
  315. var searchLowerCodeNew = searchLowerCodes[searchI]
  316. if(searchLowerCode === searchLowerCodeNew) continue // doesn't make sense to transpose a repeat char
  317. }
  318. matchesSimpleLen = searchI
  319. targetI = matchesSimple[matchesSimpleLen - 1] + 1
  320. break
  321. }
  322. }
  323. }
  324. var searchI = 0
  325. var typoStrictI = 0
  326. var successStrict = false
  327. var matchesStrictLen = 0
  328. var nextBeginningIndexes = prepared._nextBeginningIndexes
  329. if(nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target)
  330. var firstPossibleI = targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1]
  331. // Our target string successfully matched all characters in sequence!
  332. // Let's try a more advanced and strict test to improve the score
  333. // only count it as a match if it's consecutive or a beginning character!
  334. if(targetI !== targetLen) for(;;) {
  335. if(targetI >= targetLen) {
  336. // We failed to find a good spot for this search char, go back to the previous search char and force it forward
  337. if(searchI <= 0) { // We failed to push chars forward for a better match
  338. // transpose, starting from the beginning
  339. ++typoStrictI; if(typoStrictI > searchLen-2) break
  340. if(searchLowerCodes[typoStrictI] === searchLowerCodes[typoStrictI+1]) continue // doesn't make sense to transpose a repeat char
  341. targetI = firstPossibleI
  342. continue
  343. }
  344. --searchI
  345. var lastMatch = matchesStrict[--matchesStrictLen]
  346. targetI = nextBeginningIndexes[lastMatch]
  347. } else {
  348. var isMatch = searchLowerCodes[typoStrictI===0?searchI : (typoStrictI===searchI?searchI+1 : (typoStrictI===searchI-1?searchI-1 : searchI))] === targetLowerCodes[targetI]
  349. if(isMatch) {
  350. matchesStrict[matchesStrictLen++] = targetI
  351. ++searchI; if(searchI === searchLen) { successStrict = true; break }
  352. ++targetI
  353. } else {
  354. targetI = nextBeginningIndexes[targetI]
  355. }
  356. }
  357. }
  358. { // tally up the score & keep track of matches for highlighting later
  359. if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen }
  360. else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen }
  361. var score = 0
  362. var lastTargetI = -1
  363. for(var i = 0; i < searchLen; ++i) { var targetI = matchesBest[i]
  364. // score only goes down if they're not consecutive
  365. if(lastTargetI !== targetI - 1) score -= targetI
  366. lastTargetI = targetI
  367. }
  368. if(!successStrict) {
  369. score *= 1000
  370. if(typoSimpleI !== 0) score += -20/*typoPenalty*/
  371. } else {
  372. if(typoStrictI !== 0) score += -20/*typoPenalty*/
  373. }
  374. score -= targetLen - searchLen
  375. prepared.score = score
  376. prepared.indexes = new Array(matchesBestLen); for(var i = matchesBestLen - 1; i >= 0; --i) prepared.indexes[i] = matchesBest[i]
  377. return prepared
  378. }
  379. },
  380. algorithmNoTypo: function(searchLowerCodes, prepared, searchLowerCode) {
  381. var targetLowerCodes = prepared._targetLowerCodes
  382. var searchLen = searchLowerCodes.length
  383. var targetLen = targetLowerCodes.length
  384. var searchI = 0 // where we at
  385. var targetI = 0 // where you at
  386. var matchesSimpleLen = 0
  387. // very basic fuzzy match; to remove non-matching targets ASAP!
  388. // walk through target. find sequential matches.
  389. // if all chars aren't found then exit
  390. for(;;) {
  391. var isMatch = searchLowerCode === targetLowerCodes[targetI]
  392. if(isMatch) {
  393. matchesSimple[matchesSimpleLen++] = targetI
  394. ++searchI; if(searchI === searchLen) break
  395. searchLowerCode = searchLowerCodes[searchI]
  396. }
  397. ++targetI; if(targetI >= targetLen) return null // Failed to find searchI
  398. }
  399. var searchI = 0
  400. var successStrict = false
  401. var matchesStrictLen = 0
  402. var nextBeginningIndexes = prepared._nextBeginningIndexes
  403. if(nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target)
  404. var firstPossibleI = targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1]
  405. // Our target string successfully matched all characters in sequence!
  406. // Let's try a more advanced and strict test to improve the score
  407. // only count it as a match if it's consecutive or a beginning character!
  408. if(targetI !== targetLen) for(;;) {
  409. if(targetI >= targetLen) {
  410. // We failed to find a good spot for this search char, go back to the previous search char and force it forward
  411. if(searchI <= 0) break // We failed to push chars forward for a better match
  412. --searchI
  413. var lastMatch = matchesStrict[--matchesStrictLen]
  414. targetI = nextBeginningIndexes[lastMatch]
  415. } else {
  416. var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI]
  417. if(isMatch) {
  418. matchesStrict[matchesStrictLen++] = targetI
  419. ++searchI; if(searchI === searchLen) { successStrict = true; break }
  420. ++targetI
  421. } else {
  422. targetI = nextBeginningIndexes[targetI]
  423. }
  424. }
  425. }
  426. { // tally up the score & keep track of matches for highlighting later
  427. if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen }
  428. else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen }
  429. var score = 0
  430. var lastTargetI = -1
  431. for(var i = 0; i < searchLen; ++i) { var targetI = matchesBest[i]
  432. // score only goes down if they're not consecutive
  433. if(lastTargetI !== targetI - 1) score -= targetI
  434. lastTargetI = targetI
  435. }
  436. if(!successStrict) score *= 1000
  437. score -= targetLen - searchLen
  438. prepared.score = score
  439. prepared.indexes = new Array(matchesBestLen); for(var i = matchesBestLen - 1; i >= 0; --i) prepared.indexes[i] = matchesBest[i]
  440. return prepared
  441. }
  442. },
  443. prepareLowerCodes: function(str) {
  444. var strLen = str.length
  445. var lowerCodes = [] // new Array(strLen) sparse array is too slow
  446. var lower = str.toLowerCase()
  447. for(var i = 0; i < strLen; ++i) lowerCodes[i] = lower.charCodeAt(i)
  448. return lowerCodes
  449. },
  450. prepareBeginningIndexes: function(target) {
  451. var targetLen = target.length
  452. var beginningIndexes = []; var beginningIndexesLen = 0
  453. var wasUpper = false
  454. var wasAlphanum = false
  455. for(var i = 0; i < targetLen; ++i) {
  456. var targetCode = target.charCodeAt(i)
  457. var isUpper = targetCode>=65&&targetCode<=90
  458. var isAlphanum = isUpper || targetCode>=97&&targetCode<=122 || targetCode>=48&&targetCode<=57
  459. var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum
  460. wasUpper = isUpper
  461. wasAlphanum = isAlphanum
  462. if(isBeginning) beginningIndexes[beginningIndexesLen++] = i
  463. }
  464. return beginningIndexes
  465. },
  466. prepareNextBeginningIndexes: function(target) {
  467. var targetLen = target.length
  468. var beginningIndexes = fuzzysort.prepareBeginningIndexes(target)
  469. var nextBeginningIndexes = [] // new Array(targetLen) sparse array is too slow
  470. var lastIsBeginning = beginningIndexes[0]
  471. var lastIsBeginningI = 0
  472. for(var i = 0; i < targetLen; ++i) {
  473. if(lastIsBeginning > i) {
  474. nextBeginningIndexes[i] = lastIsBeginning
  475. } else {
  476. lastIsBeginning = beginningIndexes[++lastIsBeginningI]
  477. nextBeginningIndexes[i] = lastIsBeginning===undefined ? targetLen : lastIsBeginning
  478. }
  479. }
  480. return nextBeginningIndexes
  481. },
  482. cleanup: cleanup,
  483. new: fuzzysortNew,
  484. }
  485. return fuzzysort
  486. } // fuzzysortNew
  487. // This stuff is outside fuzzysortNew, because it's shared with instances of fuzzysort.new()
  488. var isNode = typeof require !== 'undefined' && typeof window === 'undefined'
  489. // var MAX_INT = Number.MAX_SAFE_INTEGER
  490. // var MIN_INT = Number.MIN_VALUE
  491. var preparedCache = new Map()
  492. var preparedSearchCache = new Map()
  493. var noResults = []; noResults.total = 0
  494. var matchesSimple = []; var matchesStrict = []
  495. function cleanup() { preparedCache.clear(); preparedSearchCache.clear(); matchesSimple = []; matchesStrict = [] }
  496. function defaultScoreFn(a) {
  497. var max = -9007199254740991
  498. for (var i = a.length - 1; i >= 0; --i) {
  499. var result = a[i]; if(result === null) continue
  500. var score = result.score
  501. if(score > max) max = score
  502. }
  503. if(max === -9007199254740991) return null
  504. return max
  505. }
  506. // prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop]
  507. // prop = 'key1.key2' 10ms
  508. // prop = ['key1', 'key2'] 27ms
  509. function getValue(obj, prop) {
  510. var tmp = obj[prop]; if(tmp !== undefined) return tmp
  511. var segs = prop
  512. if(!Array.isArray(prop)) segs = prop.split('.')
  513. var len = segs.length
  514. var i = -1
  515. while (obj && (++i < len)) obj = obj[segs[i]]
  516. return obj
  517. }
  518. function isObj(x) { return typeof x === 'object' } // faster as a function
  519. // Hacked version of https://github.com/lemire/FastPriorityQueue.js
  520. var fastpriorityqueue=function(){var r=[],o=0,e={};function n(){for(var e=0,n=r[e],c=1;c<o;){var f=c+1;e=c,f<o&&r[f].score<r[c].score&&(e=f),r[e-1>>1]=r[e],c=1+(e<<1)}for(var a=e-1>>1;e>0&&n.score<r[a].score;a=(e=a)-1>>1)r[e]=r[a];r[e]=n}return e.add=function(e){var n=o;r[o++]=e;for(var c=n-1>>1;n>0&&e.score<r[c].score;c=(n=c)-1>>1)r[n]=r[c];r[n]=e},e.poll=function(){if(0!==o){var e=r[0];return r[0]=r[--o],n(),e}},e.peek=function(e){if(0!==o)return r[0]},e.replaceTop=function(o){r[0]=o,n()},e};
  521. var q = fastpriorityqueue() // reuse this, except for async, it needs to make its own
  522. return fuzzysortNew()
  523. }) // UMD
  524. // TODO: (performance) wasm version!?
  525. // TODO: (performance) layout memory in an optimal way to go fast by avoiding cache misses
  526. // TODO: (performance) preparedCache is a memory leak
  527. // TODO: (like sublime) backslash === forwardslash
  528. // TODO: (performance) i have no idea how well optimized the allowing typos algorithm is