### Install fuzzball.js with NPM Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Install the library using npm for Node.js projects. ```bash npm install fuzzball ``` -------------------------------- ### Pre-process Strings for Token Sort Ratio Standalone Source: https://github.com/nol13/fuzzball.js/blob/master/README.md For standalone 'token_sort' scorer functions, set options.proc_sorted to true and pre-process both strings. This example demonstrates processing and sorting strings before calculating the token sort ratio. ```javascript str1 = "Abe Lincoln"; str2 = "Lincoln, Abe"; str1 = fuzz.process_and_sort(fuzz.full_process(str1)); str2 = fuzz.process_and_sort(fuzz.full_process(str2)); fuzz.token_sort_ratio(str1, str2, {proc_sorted: true}); 100 ``` -------------------------------- ### Define Processor for Multiple Fields Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Example of a processor function that combines multiple fields from a choice object into a single string for scoring. This allows matching based on concatenated values. ```javascript processor = choice => choice.field1 + " " + choice.field2; ``` -------------------------------- ### Basic fuzzball.js Usage Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Demonstrates basic string comparison using ratio and token_set_ratio. Also shows how to use extract with custom options and how results are returned. ```javascript fuzz = require('fuzzball'); fuzz.ratio("hello world", "hiyyo wyrld"); 64 fuzz.token_set_ratio("fuzzy was a bear", "a fuzzy bear fuzzy was"); 100 options = {scorer: fuzz.token_set_ratio}; choices = ["Hood, Harry", "Mr. Minor", "Mr. Henry Hood"]; fuzz.extract("mr. harry hood", choices, options); // [choice, score, index/key] [ [ 'Hood, Harry', 100, 0 ], [ 'Mr. Henry Hood', 85, 2 ], [ 'Mr. Minor', 40, 1 ] ] /** * Set options.returnObjects = true to get back * an array of {choice, score, key} objects instead of tuples */ results = await fuzz.extractAsPromised("mr. harry hood", choices, options); // Cancel search const abortController = new AbortController(); options.abortController = abortController; fuzz.extractAsPromised("gonna get canceled", choices, options) .then(res => {/* do stuff */}) .catch((e) => { if (e.message === 'aborted') console.log('Search was aborted!') }); abortController.abort(); ``` -------------------------------- ### Ratio Calculation with Options Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Demonstrates using options to control pre-processing. Setting `full_process` to `false` disables default stripping of non-alphanumeric characters and lowercasing. ```javascript // Eh, don't need to clean it up.. // Set options.force_ascii to true to remove all non-ascii letters as well, default: false fuzz.ratio("this is a test", "this is a test!", {full_process: false}); 97 ``` -------------------------------- ### Manual Full Processing Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Shows how to manually run the full processing function, which strips non-alphanumeric characters and collapses whitespace by default. The `force_ascii` option can be used to remove non-ASCII characters. ```javascript // force_ascii will strip out non-ascii characters except designated wildcards fuzz.full_process("myt^eäXt!"); myt eäxt ``` ```javascript fuzz.full_process("myt^eäXt!", {force_ascii: true}); myt ext ``` -------------------------------- ### Pre-process Choices for Token Set Ratio with Extract Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Optimize 'token_set' scorer performance with the extract function by setting the 'tokens' property of each choice object. Processor functions are ignored when 'tokens' is set. Ensure choices are objects. ```javascript query = fuzz.full_process("126-Abzx"); choices = [{id: 345, model: "123-abc"}, {id: 346, model: "efg-123"}, {id: 347, model: "456 abdzx"}]; for (choice of choices) { choice.tokens = fuzz.unique_tokens(fuzz.full_process(choice.model)); } options = { scorer: fuzz.token_set_ratio, full_process: false }; results = fuzz.extract(query, choices, options); ``` -------------------------------- ### Use Difflib Ratio Calculation Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Specify options.ratio_alg = "difflib" to use difflib's ratio function for all ratio calculations. This method is based on matching characters rather than edit distance. Note that not all features are supported when using difflib. ```javascript If you want to use difflib's ratio function for all ratio calculations, which differs slightly from the default python-Levenshtein style behavior, you can specify options.ratio_alg = "difflib". ``` -------------------------------- ### WRatio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates a weighted ratio between two strings by considering the best score from various comparison methods. This provides a comprehensive similarity score. ```APIDOC ## fuzzball~WRatio(str1, str2, [options_p]) ### Description Calculate weighted ratio of the two strings, taking best score of various methods. ### Parameters #### Parameters - **str1** (string) - The first string. - **str2** (string) - The second string. - **[options_p]** (Object) - Additional options. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **[options_p.collapseWhitespace]** (boolean) - Collapse consecutive white space during full_process, default true - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided - **[options_p.astral]** (number) - Use astral aware calculation - **[options_p.normalize]** (string) - Normalize unicode representations ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### Include fuzzball.js in HTML (Module) Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Import specific functions from the ES module bundle in an HTML file for modern browser usage. ```html ``` -------------------------------- ### Include fuzzball.js in HTML (UMD) Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Include the UMD bundle in an HTML file for browser usage. Ensure the script tag has UTF-8 charset if the page is not already set to it. ```html ``` -------------------------------- ### Cancel Asynchronous Extraction with AbortController Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Shows how to use AbortController to cancel an ongoing asynchronous fuzzy search operation. The promise will reject with an 'aborted' error message if cancellation is successful. `asyncLoopOffset` can be adjusted for performance tuning, though defaults are usually optimal. ```javascript // or use AbortController to cancel search const abortController = new AbortController(); options.abortController = abortController; options.asyncLoopOffset = 64; fuzz.extractAsPromised("gonna get aborted", choices, options) .then(res => {/* do stuff */}) .catch((e) => { if (e.message === 'aborted') console.log('I got aborted!') }); abortController.abort(); ``` -------------------------------- ### Calculate Token Similarity Sort Ratio Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Compares strings using token similarity for sorting instead of alphabetical order. This can be more accurate when token order is less important than content, but may perform slower. It can be enabled for token_set_ratio by setting sortBySimilarity to true. ```javascript fuzz.token_sort_ratio('apple cup zebrah horse foo', 'zapple cub horse bebrah bar') 58 ``` ```javascript fuzz.token_set_ratio('apple cup zebrah horse foo', 'zapple cub horse bebrah bar') 61 ``` ```javascript fuzz.token_similarity_sort_ratio('apple cup zebrah horse foo', 'zapple cub horse bebrah bar') 68 ``` ```javascript fuzz.token_set_ratio('apple cup zebrah horse foo', 'zapple cub horse bebrah bar', {sortBySimilarity: true}) 71 ``` -------------------------------- ### Calculate Token Sort Ratio Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Compares strings after tokenizing, sorting tokens alphabetically, and then recombining. This is useful for comparing strings where word order might differ. ```javascript fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear"); 91 ``` ```javascript fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear"); 100 ``` -------------------------------- ### Disable Autojunk Heuristic with Difflib Source: https://github.com/nol13/fuzzball.js/blob/master/README.md When using difflib for ratio calculations, you can set options.autojunk to false to disable the automatic junk heuristic. This heuristic treats popular elements as junk. ```javascript When using difflib, you can also set `options.autojunk` to `false` to disable the automatic junk heuristic that treats popular elements as junk. ``` -------------------------------- ### Default Ratio Calculation Formula Source: https://github.com/nol13/fuzzball.js/blob/master/README.md The default ratio calculation (excluding difflib) uses the formula ((str1.length + str2.length) - distance) / (str1.length + str2.length), where distance has a substitution cost of 2. This follows python-Levenshtein behavior. ```javascript Except when using difflib, the ratios are calculated as ((str1.length + str2.length) - distance) / (str1.length + str2.length), where distance is calculated with a substitution cost of 2. This follows the behavior of python-Levenshtein, however the fuzz.distance function still uses a cost of 1 by default for all operations if just calculating distance and not a ratio. ``` -------------------------------- ### Extract Matches Returning Objects Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Configures fuzz.extract to return detailed objects for each match, including the choice, score, and key. Useful for more structured results. ```javascript options = {returnObjects: true} results = fuzz.extract(query, choicesObj, options); [ { choice: 'polar bear', score: 100, key: 'id2' }, { choice: 'koala bear', score: 80, key: 'id3' }, { choice: 'brown bear', score: 60, key: 'id1' } ] ``` -------------------------------- ### fuzzball.token_set_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the token set ratio between two strings. This method is robust to differences in word order and the presence of extra words. ```APIDOC ## fuzzball~token_set_ratio(str1, str2, [options_p]) ### Description Calculate token set ratio of the two strings. ### Parameters #### Path Parameters - **str1** (string) - Required - the first string. - **str2** (string) - Required - the second string. #### Query Parameters - **options_p** (Object) - Optional - Additional options. - **useCollator** (boolean) - Optional - Use `Intl.Collator` for locale-sensitive string comparison. - **full_process** (boolean) - Optional - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **force_ascii** (boolean) - Optional - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **trySimple** (boolean) - Optional - try simple/partial ratio as part of (parial_)token_set_ratio test suite - **sortBySimilarity** (boolean) - Optional - sort tokens by similarity to each other before combining instead of alphabetically - **wildcards** (string) - Optional - characters that will be used as wildcards if provided - **astral** (number) - Optional - Use astral aware calculation - **normalize** (string) - Optional - Normalize unicode representations - **ratio_alg** (string) - Optional - a string representing the ratio algorithm to use, either "levenshtein" or "difflib", default "levenshtein" - **autojunk** (boolean) - Optional - autojunk argument passed to difflib if you're using the ratio_alg option, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### Enable Wildcard Awareness in Unique Tokens Source: https://github.com/nol13/fuzzball.js/blob/master/README.md To enable wildcard awareness in fuzz.unique_tokens, pass options to it as the second argument. This is useful when using wildcards. ```javascript Pass options to fuzz.unique_tokens as the second argument if you're using wildcards for it to be wildcard aware. ``` -------------------------------- ### Pre-process Choices for Token Sort Ratio with Extract Source: https://github.com/nol13/fuzzball.js/blob/master/README.md When using the 'token_sort' scorer with the extract function, pre-process choices by setting the 'proc_sorted' property to improve performance. Ensure each choice is an object. ```javascript query = fuzz.full_process("126-Abzx"); choices = [{id: 345, model: "123-abc"}, {id: 346, model: "efg-123"}, {id: 347, model: "456 abdzx"}]; for (choice of choices) { choice.proc_sorted = fuzz.process_and_sort(fuzz.full_process(choice.model)); } options = { scorer: fuzz.token_sort_ratio, full_process: false }; results = fuzz.extract(query, choices, options); ``` -------------------------------- ### Pre-process Strings for Token Set Ratio Standalone Source: https://github.com/nol13/fuzzball.js/blob/master/README.md When using 'token_set' scorer as standalone functions, tokenize both strings beforehand and attach them to options.tokens as a two-element array. The first two arguments are still required for validation but not used for scoring. ```javascript str1 = "fluffy head man"; str2 = "heady fluffy head"; str1_tokens = fuzz.unique_tokens(fuzz.full_process(str1)); str2_tokens = fuzz.unique_tokens(fuzz.full_process(str2)); options = {tokens: [str1_tokens, str2_tokens]}; // Still have to include first two args for validation but they won't be used for scoring fuzz.token_set_ratio(str1, str2, options); 85 ``` -------------------------------- ### fuzzball.partial_token_set_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the partial token set ratio between two strings. This is a variation of token set ratio that focuses on partial matches. ```APIDOC ## fuzzball~partial_token_set_ratio(str1, str2, [options_p]) ### Description Calculate partial token ratio of the two strings. ### Parameters #### Path Parameters - **str1** (string) - Required - the first string. - **str2** (string) - Required - the second string. #### Query Parameters - **options_p** (Object) - Optional - Additional options. - **useCollator** (boolean) - Optional - Use `Intl.Collator` for locale-sensitive string comparison. - **full_process** (boolean) - Optional - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **force_ascii** (boolean) - Optional - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **trySimple** (boolean) - Optional - try simple/partial ratio as part of (parial_)token_set_ratio test suite - **sortBySimilarity** (boolean) - Optional - sort tokens by similarity to each other before combining instead of alphabetically - **wildcards** (string) - Optional - characters that will be used as wildcards if provided - **astral** (number) - Optional - Use astral aware calculation - **normalize** (string) - Optional - Normalize unicode representations - **autojunk** (boolean) - Optional - autojunk argument passed to difflib, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### Calculate Simple Ratio Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Calculates the simple ratio between two strings. Non-alphanumeric characters are stripped and strings are lowercased by default. ```javascript // "!" Stripped and lowercased in pre-processing by default fuzz.ratio("this is a test", "This is a test!"); 100 ``` -------------------------------- ### Custom Scorer for Complex Matching Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Demonstrates defining a custom scorer function for advanced matching logic, such as weighted scores or conditional scoring based on multiple properties. The scorer must handle the types of query and choice provided. ```javascript query = {name: "tiger", gender: "female"} choices = [{name: "tigger", gender: "male"}, {name: "lulu", gender: "female"}, {name: "chad ochocinco", gender: "male"}] function myCustomScorer(query, choice, options) { if (query.gender !== choice.gender) return 0; else return fuzz.ratio(query.name, choice.name, options); } options = {scorer: myCustomScorer} results = fuzz.extract(query, choices, options); ``` -------------------------------- ### fuzzball.partial_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates a partial ratio between two strings. This is useful when you want to find the best matching substring of a longer string. ```APIDOC ## fuzzball.partial_ratio ### Description Calculate levenshtein ratio of the two strings. ### Method `partial_ratio(str1, str2, [options_p])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **str1** (string) - The first string. * **str2** (string) - The second string. * **[options_p]** (Object) - Additional options. * **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. * **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true * **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true * **[options_p.collapseWhitespace]** (boolean) - Collapse consecutive white space during full_process, default true * **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided * **[options_p.astral]** (number) - Use astral aware calculation * **[options_p.normalize]** (string) - Normalize unicode representations * **[options_p.ratio_alg]** (string) - a string representing the ratio algorithm to use, either "levenshtein" or "difflib", default "levenshtein" * **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib if you're using the ratio_alg option, default true ### Returns * **number** - The Levenshtein ratio (0-100). ``` -------------------------------- ### Calculate Token Set Ratio Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Calculates the highest of three scores based on token intersection and differences between the two strings. This is robust against extra words in either string. ```javascript fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear"); 84 ``` ```javascript fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear"); 100 ``` -------------------------------- ### Ratio Calculation with Astral Symbols Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Handles strings containing astral symbols (Unicode code points beyond the Basic Multilingual Plane) by setting `astral` to `true`. This ensures these symbols are treated as single characters. Normalization is true by default when `astral` is true. ```javascript options = {astral: true}; fuzz.ratio("ab🐴c", "ab🐴d", options); 75 ``` -------------------------------- ### Use Wildcards in Fuzzy Matching Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Configure options to use wildcard characters for calculating edit distance. Wildcards are case-insensitive by default. Note: Wildcards are not supported when astral is true. ```javascript options = {wildcards: "*x"}; // '*' and 'x' are both wildcards fuzz.ratio('fuzzba*l', 'fuXxball', options); 100 ``` -------------------------------- ### fuzzball.partial_token_sort_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the partial token sort ratio between two strings. This is useful when one string is a substring of another. ```APIDOC ## fuzzball~partial_token_sort_ratio(str1, str2, [options_p]) ### Description Calculate partial token sort ratio of the two strings. ### Method ```javascript fuzzball.partial_token_sort_ratio(str1, str2, options_p) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **str1** (string) - The first string. - **str2** (string) - The second string. - **[options_p]** (Object) - Additional options. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided - **[options_p.astral]** (number) - Use astral aware calculation - **[options_p.normalize]** (string) - Normalize unicode representations - **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### fuzzball.partial_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the partial Levenshtein ratio between two strings. This is useful when you want to find the best partial match of a shorter string within a longer string. ```APIDOC ## fuzzball~partial_ratio(str1, str2, [options_p]) ### Description Calculate partial levenshtein ratio of the two strings. ### Parameters #### Path Parameters - **str1** (string) - Required - the first string. - **str2** (string) - Required - the second string. #### Query Parameters - **options_p** (Object) - Optional - Additional options. - **useCollator** (boolean) - Optional - Use `Intl.Collator` for locale-sensitive string comparison. - **full_process** (boolean) - Optional - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **force_ascii** (boolean) - Optional - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **collapseWhitespace** (boolean) - Optional - Collapse consecutive white space during full_process, default true - **wildcards** (string) - Optional - characters that will be used as wildcards if provided - **astral** (number) - Optional - Use astral aware calculation - **normalize** (string) - Optional - Normalize unicode representations - **autojunk** (boolean) - Optional - autojunk argument passed to difflib, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### partial_token_similarity_sort_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the token sort ratio similarity between two strings. This method is useful for comparing strings where word order might differ but the words themselves are important. ```APIDOC ## fuzzball~partial_token_similarity_sort_ratio(str1, str2, [options_p]) ### Description Calculate token sort ratio of the two strings. ### Parameters #### Parameters - **str1** (string) - The first string. - **str2** (string) - The second string. - **[options_p]** (Object) - Additional options. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided - **[options_p.astral]** (number) - Use astral aware calculation - **[options_p.normalize]** (string) - Normalize unicode representations - **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### Ratio Calculation with Collator Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Enables collation for edit distance calculation by setting `useCollator` to `true`. This can impact performance and is useful for handling different language character sets correctly. ```javascript options = {useCollator: true}; fuzz.ratio("this is ä test", "this is a test", options); 100 ``` -------------------------------- ### Extract Matches from Array of Strings Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Finds the best matches for a query string within an array of choices. The scorer defaults to fuzz.ratio if not specified. Returns an array of [choice, score, index]. ```javascript query = "polar bear"; choices = ["brown bear", "polar bear", "koala bear"]; results = fuzz.extract(query, choices); // [choice, score, index] [ [ 'polar bear', 100, 1 ], [ 'koala bear', 80, 2 ], [ 'brown bear', 60, 0 ] ] ``` -------------------------------- ### fuzz.extract Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Extracts matching choices from a list based on a query string. This is the synchronous version of the extract function. ```APIDOC ## fuzz.extract(query, choices, options) ### Description Extracts matching choices from a list based on a query string. This is the synchronous version of the fuzzy matching function. ### Method `extract` ### Parameters - **query** (string | object) - The string or object to search for. - **choices** (array | object) - The list of choices to search within. Can be an array of strings, an object with string values, an array of objects, or an object where values are choices. - **options** (object) - Optional configuration object for scoring, processing, and other behaviors. - **scorer** (function) - A function that takes two values and returns a score. Defaults to `fuzz.ratio`. - **processor** (function) - A function that takes a choice and returns the string to be used for scoring. Must be supplied if choices are not already strings. - **limit** (number) - The maximum number of top results to return. Defaults to no limit (0). - **cutoff** (number) - The lowest score to return. Defaults to 0. - **unsorted** (boolean) - If true, results will not be sorted. Defaults to false. If true, `limit` will be ignored. - **returnObjects** (boolean) - If true, results will be returned as objects containing `choice`, `score`, and `key`/`index`. Defaults to false. ### Request Example ```javascript const fuzz = require('fuzzball'); const query = "polar bear"; const choices = ["brown bear", "polar bear", "koala bear"]; const options = { returnObjects: true }; const results = fuzz.extract(query, choices, options); // [ { choice: 'polar bear', score: 100, index: 1 }, ... ] ``` ### Response #### Success Response - **results** (array) - An array of matching choices. Each element can be in the format `[choice, score, index/key]` or an object `{ choice, score, key/index }` if `returnObjects` is true. ``` -------------------------------- ### Extract Matches with Options and Processor Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Advanced extraction using options like custom scorers, processors, limits, and cutoffs. The processor function extracts the string to be scored from complex choices. Ensure the query is processed similarly for unbiased results. ```javascript query = "126abzx"; choices = [{id: 345, model: "123abc"}, {id: 346, model: "123efg"}, {id: 347, model: "456abdzx"}]; options = { scorer: fuzz.partial_ratio, // Any function that takes two values and returns a score, default: ratio processor: choice => choice.model, // Takes choice object, returns string, default: no processor. Must supply if choices are not already strings. limit: 2, // Max number of top results to return, default: no limit / 0. cutoff: 50, // Lowest score to return, default: 0 unsorted: false // Results won't be sorted if true, default: false. If true limit will be ignored. }; results = fuzz.extract(query, choices, options); // [choice, score, index/key] [ [ { id: 347, model: '456abdzx' }, 71, 2 ], [ { id: 345, model: '123abc' }, 67, 0 ] ] ``` -------------------------------- ### fuzzball.partial_token_similarity_sort_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the partial token similarity sort ratio between two strings. This is a variation of token similarity sort ratio. ```APIDOC ## fuzzball~partial_token_similarity_sort_ratio(str1, str2, [options_p]) ### Description Calculate partial token similarity sort ratio of the two strings. ### Method ```javascript fuzzball.partial_token_similarity_sort_ratio(str1, str2, options_p) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **str1** (string) - The first string. - **str2** (string) - The second string. - **[options_p]** (Object) - Additional options. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided - **[options_p.astral]** (number) - Use astral aware calculation - **[options_p.normalize]** (string) - Normalize unicode representations - **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### fuzzball.token_sort_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the token sort ratio between two strings. This method sorts the tokens of each string alphabetically and then compares them. ```APIDOC ## fuzzball~token_sort_ratio(str1, str2, [options_p]) ### Description Calculate token sort ratio of the two strings. ### Method ```javascript fuzzball.token_sort_ratio(str1, str2, options_p) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **str1** (string) - The first string. - **str2** (string) - The second string. - **[options_p]** (Object) - Additional options. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided - **[options_p.astral]** (number) - Use astral aware calculation - **[options_p.normalize]** (string) - Normalize unicode representations - **[options_p.ratio_alg]** (string) - a string representing the ratio algorithm to use, either "levenshtein" or "difflib", default "levenshtein" - **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib if you're using the ratio_alg option, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### fuzzball.token_similarity_sort_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the token similarity sort ratio between two strings. This is similar to token sort ratio but focuses on similarity. ```APIDOC ## fuzzball~token_similarity_sort_ratio(str1, str2, [options_p]) ### Description Calculate token sort ratio of the two strings. ### Method ```javascript fuzzball.token_similarity_sort_ratio(str1, str2, options_p) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **str1** (string) - The first string. - **str2** (string) - The second string. - **[options_p]** (Object) - Additional options. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided - **[options_p.astral]** (number) - Use astral aware calculation - **[options_p.normalize]** (string) - Normalize unicode representations - **[options_p.ratio_alg]** (string) - a string representing the ratio algorithm to use, either "levenshtein" or "difflib", default "levenshtein" - **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib if you're using the ratio_alg option, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### Calculate Partial Ratio Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Calculates the highest scoring substring of the longer string against the shorter string. Useful when one string might be a substring of another. ```javascript // Still 100, substring of 2nd is a perfect match of the first fuzz.partial_ratio("test", "testing"); 100 ``` -------------------------------- ### fuzz.extractAsPromised Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Extracts matching choices from a list based on a query string. Returns a Promise that resolves with the results. The Promise will not be polyfilled. ```APIDOC ## fuzz.extractAsPromised(query, choices, options) ### Description Extracts matching choices from a list based on a query string and returns a Promise with the results. This function is useful for asynchronous operations where you need to handle the results later. ### Method `extractAsPromised` ### Parameters - **query** (string | object) - The string or object to search for. - **choices** (array | object) - The list of choices to search within. Can be an array of strings, an object with string values, an array of objects, or an object where values are choices. - **options** (object) - Optional configuration object for scoring, processing, and other behaviors. - **scorer** (function) - A function that takes two values and returns a score. Defaults to `fuzz.ratio`. - **processor** (function) - A function that takes a choice and returns the string to be used for scoring. Must be supplied if choices are not already strings. - **limit** (number) - The maximum number of top results to return. Defaults to no limit (0). - **cutoff** (number) - The lowest score to return. Defaults to 0. - **unsorted** (boolean) - If true, results will not be sorted. Defaults to false. If true, `limit` will be ignored. - **returnObjects** (boolean) - If true, results will be returned as objects containing `choice`, `score`, and `key`/`index`. Defaults to false. - **abortController** (AbortController) - An AbortController instance to cancel the search operation. - **asyncLoopOffset** (number) - Controls the frequency of asynchronous operations within the loop. Defaults to 256. ### Request Example ```javascript const fuzz = require('fuzzball'); const query = "polar bear"; const choices = ["brown bear", "polar bear", "koala bear"]; const options = { returnObjects: true, scorer: fuzz.partial_ratio, processor: choice => choice.model, // Example if choices were objects limit: 2, cutoff: 50 }; fuzz.extractAsPromised(query, choices, options) .then(results => { console.log(results); // Example output if returnObjects is true: // [ { choice: 'polar bear', score: 100, index: 1 }, ... ] }) .catch(err => { console.error(err); }); ``` ### Response #### Success Response (Promise resolves with) - **results** (array) - An array of matching choices. Each element can be in the format `[choice, score, index/key]` or an object `{ choice, score, key/index }` if `returnObjects` is true. ``` -------------------------------- ### fuzzball.extractAsync Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Asynchronously extracts the top scoring items from a list of choices based on a query string. This method is useful for scenarios where performance is critical and asynchronous operations are preferred. ```APIDOC ## fuzzball~extractAsync(query, choices, [options_p], callback) ### Description Return the top scoring items from an array (or assoc array) of choices. ### Method Asynchronous function call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **query** (string) - Required - the search term. - **choices** (Array | Array | Object) - Required - array of strings, or array of choice objects if processor is supplied, or object of form {key: choice}. - **[options_p]** (Object) - Optional - Additional options. - **[options_p.scorer]** (function) - takes two values and returns a score, will be passed options as 3rd argument. - **[options_p.processor]** (function) - takes each choice and outputs a value to be used for Scoring. - **[options_p.limit]** (number) - optional max number of results to return, returns all if not supplied. - **[options_p.cutoff]** (number) - minimum score that will get returned 0-100. - **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. - **[options_p.astral]** (number) - Use astral aware calculation. - **[options_p.normalize]** (string) - Normalize unicode representations. - **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true. - **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default false. - **[options_p.collapseWhitespace]** (boolean) - Collapse consecutive white space during full_process, default true. - **[options_p.trySimple]** (boolean) - try simple/partial ratio as part of (parial_)token_set_ratio test suite. - **[options_p.sortBySimilarity]** (boolean) - sort tokens by similarity to each other before combining instead of alphabetically. - **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided. - **[options_p.returnObjects]** (boolean) - return array of object instead of array of tuples; default false. - **[options_p.abortController]** (Object) - track abortion. - **[options_p.cancelToken]** (Object) - track cancellation. - **[options_p.asyncLoopOffset]** (number) - number of rows to run in between every async loop iteration, default 256. - **[options_p.ratio_alg]** (string) - a string representing the ratio algorithm to use, either "levenshtein" or "difflib", default "levenshtein". - **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib if you're using the ratio_alg option, default true. - **callback** (function) - Required - node style callback (err, arrayOfResults). ### Request Example None ### Response #### Success Response (200) - **arrayOfResults** (Array) - An array of the top scoring items. #### Response Example None ``` -------------------------------- ### fuzzball.ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the Levenshtein ratio between two strings. This is a normalized score representing the similarity between two strings, ranging from 0 to 100. ```APIDOC ## fuzzball.ratio ### Description Calculates the Levenshtein ratio of the two strings. ### Method `ratio(str1, str2, [options_p])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **str1** (string) - The first string. * **str2** (string) - The second string. * **[options_p]** (Object) - Additional options. * **[options_p.useCollator]** (boolean) - Use `Intl.Collator` for locale-sensitive string comparison. * **[options_p.full_process]** (boolean) - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true * **[options_p.force_ascii]** (boolean) - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true * **[options_p.collapseWhitespace]** (boolean) - Collapse consecutive white space during full_process, default true * **[options_p.wildcards]** (string) - characters that will be used as wildcards if provided * **[options_p.astral]** (number) - Use astral aware calculation * **[options_p.normalize]** (string) - Normalize unicode representations * **[options_p.ratio_alg]** (string) - a string representing the ratio algorithm to use, either "levenshtein" or "difflib", default "levenshtein" * **[options_p.autojunk]** (boolean) - autojunk argument passed to difflib if you're using the ratio_alg option, default true ### Returns * **number** - The Levenshtein ratio (0-100). ``` -------------------------------- ### fuzzball.token_sort_ratio Source: https://github.com/nol13/fuzzball.js/blob/master/jsdocs/fuzzball.md Calculates the token sort ratio between two strings. This method sorts the tokens alphabetically before comparing them, making it sensitive to word order. ```APIDOC ## fuzzball~token_sort_ratio(str1, str2, [options_p]) ### Description Calculate token sort ratio of the two strings. ### Parameters #### Path Parameters - **str1** (string) - Required - the first string. - **str2** (string) - Required - the second string. #### Query Parameters - **options_p** (Object) - Optional - Additional options. - **useCollator** (boolean) - Optional - Use `Intl.Collator` for locale-sensitive string comparison. - **full_process** (boolean) - Optional - Apply basic cleanup, non-alphanumeric to whitespace etc. if true. default true - **force_ascii** (boolean) - Optional - Strip non-ascii in full_process if true (non-ascii will not become whtespace), only applied if full_process is true as well, default true - **sortBySimilarity** (boolean) - Optional - sort tokens by similarity to each other before combining instead of alphabetically - **wildcards** (string) - Optional - characters that will be used as wildcards if provided - **astral** (number) - Optional - Use astral aware calculation - **normalize** (string) - Optional - Normalize unicode representations - **autojunk** (boolean) - Optional - autojunk argument passed to difflib, default true ### Returns - **number** - the levenshtein ratio (0-100). ``` -------------------------------- ### Extract Matches from Object with String Values Source: https://github.com/nol13/fuzzball.js/blob/master/README.md Finds matches for a query string within an object where values are strings. Returns an array of [choice, score, key]. ```javascript query = "polar bear"; choicesObj = { id1: "brown bear", id2: "polar bear", id3: "koala bear"}; results = fuzz.extract(query, choicesObj); // [choice, score, key] [ [ 'polar bear', 100, 'id2' ], [ 'koala bear', 80, 'id3' ], [ 'brown bear', 60, 'id1' ] ] ```