|
| 1 | +const binding = require('node-gyp-build')(__dirname) |
| 2 | + |
| 3 | +const defaultPathSeparator = process.platform === "win32" ? '\\' : '/' |
| 4 | + |
| 5 | +function parseOptions(options, query) { |
| 6 | + // options.allowErrors ? = false |
| 7 | + if (options.usePathScoring == undefined) |
| 8 | + options.usePathScoring = true |
| 9 | + // options.useExtensionBonus ? = false |
| 10 | + if (!options.pathSeparator) |
| 11 | + options.pathSeparator = defaultPathSeparator |
| 12 | + // options.optCharRegEx ? = null |
| 13 | + // options.wrap ? = null |
| 14 | + if (!options.maxResults) |
| 15 | + options.maxResults = 0 |
| 16 | + return options |
| 17 | +} |
| 18 | + |
| 19 | +class FuzzaldrinPlusFast { |
| 20 | + constructor() { |
| 21 | + this.obj = new binding.Fuzzaldrin() |
| 22 | + } |
| 23 | + |
| 24 | + setCandidates(candidates, options = {}) { |
| 25 | + this.candidates = candidates |
| 26 | + if (options.key) |
| 27 | + candidates = candidates.map((item) => item[options.key]) |
| 28 | + return this.obj.setCandidates(candidates) |
| 29 | + } |
| 30 | + |
| 31 | + filter(query, options = {}) { |
| 32 | + options = parseOptions(options) |
| 33 | + const res = this.obj.filter(query, options.maxResults, |
| 34 | + Boolean(options.usePathScoring), Boolean(options.useExtensionBonus)) |
| 35 | + return res.map((ind) => this.candidates[ind]) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +module.exports = { |
| 40 | + New: () => new FuzzaldrinPlusFast(), |
| 41 | + |
| 42 | + filter: (candidates, query, options = {}) => { |
| 43 | + if (!candidates || !query) |
| 44 | + return [] |
| 45 | + const obj = new FuzzaldrinPlusFast() |
| 46 | + obj.setCandidates(candidates, options) |
| 47 | + return obj.filter(query, options) |
| 48 | + }, |
| 49 | + |
| 50 | + score: (candidate, query, options = {}) => { |
| 51 | + if (!candidate || !query) |
| 52 | + return 0 |
| 53 | + options = parseOptions(options) |
| 54 | + return binding.score(candidate, query, |
| 55 | + Boolean(options.usePathScoring), Boolean(options.useExtensionBonus)) |
| 56 | + }, |
| 57 | + |
| 58 | + match: (string, query, options = {}) => { |
| 59 | + if (!string || !query) |
| 60 | + return [] |
| 61 | + if (string == query) |
| 62 | + return Array.from(Array(string.length).keys()) |
| 63 | + options = parseOptions(options, query) |
| 64 | + return binding.match(string, query, options.pathSeparator) |
| 65 | + }, |
| 66 | + |
| 67 | + wrap: (string, query, options = {}) => { |
| 68 | + if (!string || !query) |
| 69 | + return [] |
| 70 | + options = parseOptions(options, query) |
| 71 | + return binding.wrap(string, query, options.pathSeparator) |
| 72 | + }, |
| 73 | + |
| 74 | + prepareQuery: (query, options = {}) => { |
| 75 | + // This is no - op since there is no major benefit by precomputing something |
| 76 | + // just for the query. |
| 77 | + return {} |
| 78 | + }, |
| 79 | +} |
0 commit comments