Jump to content
UBot Underground

Trouble returning a value from Javascript $eval


Recommended Posts

Ok, I am at it again with my fuzzy matching javascript algorithm. The original link can be found here http://www.ubotstudio.com/forum/index.php?/topic/14573-adapting-a-javascript-prototype-object-to-a-ubot-script/ .  The new script has some additional features, namely (1) returns the exact name that was matched and (2) can check the name against a list, rather than a 1:1 setup (as before).  Eventually, I'd like to adapt it to take an entire string and return the index number of where it found the fuzzy match (see end of this post).  Anyway, I have a new script I downloaded from the following links...

I am using the following additional code below to generate a fuzzy match number (between 0 and 1) and the exact name it matched (e.g. "08,testa").  #word1 is loaded into the array, while #word2 is then compared to that array (length 1 in this case).

a = FuzzySet();
a.add(\"{#word1}\");
var value = a.get(\"{#word2}\");
document.write(value); // can only see these results
value; //this value not returned

The goal is to return the value "0.8,testa" as a result to uBot for further processing.  As you can see, I have also have a "document.write()". When I run the above code, I am only able to see the results (which are correct) from the "document.write()" function (generated in HTML window).  However, I am unable to output the results returned by calling "value;" to an "alert()", "set()", etc.
 

  1. I have tried almost everything.  In the attached code (text file below), I have also included a "navigate()" to Google after reading this thread http://www.ubotstudio.com/forum/index.php?/topic/12515-what-happened-to-javascript/  . No luck.
  2. I have returned the value directly, using "a.get({#word2});".  However, this was wrong in my original code http://www.ubotstudio.com/forum/index.php?/topic/14573-adapting-a-javascript-prototype-object-to-a-ubot-script/  . I have tried both setting it as a var and returning the results directly. no luck.
  3. I would prefer not to 'scrape' my own generated source code (from "document.write()" above), but can see almost no other option.

After everything, I have narrowed it down to the fact that "value" retains string "0.8,testa" when outputting the HTML code to the direct window.  However, I think that a "null" value is being returned when I simply call the variable "value;". 

 

On a side note, if any of the above examples use JavaScript reserve words, that is not the ultimate problem.  I have swapped out the variables multiple times, and that still does not seem to help. 

 

Any help would be greatly appreciated.

 

• OH, and if the solution above is simple, then I have a 2nd question.  Is there any way to load a list of names into the code above from uBot into the JavaScript array AND have it remain for  a set amount of time?  In other words, rather than using nested loops in uBot and (%ListA vs %ListB, for example) and running through the code on a 1:1 basis, is it possible to have %ListA loaded into the JavaScript and then feed %ListB (from uBot) and simplify the code view by having a single loop().  Reason I ask is that the returned values of the fuzzy match can easily be added and would make it that much more useful (see Line 186 below).

 

Line 186: (e.g. "0.8,testa")

newResults.push([results[i][0], this.exactSet[results[i][1]]]);

Sample Script.txt

Link to post
Share on other sites

FINALLY got it working!

 

So, as a gift, I present this updated code.  I'v gotten a LOT of help over the past few months, so this is my way way of giving something more than a simple "thank you".  You can read the (ton of) comments if you like, otherwise, just 'use it'.  A few quick things...

  1. Takes two test strings (as #List1 and #List2, separated by ",").  You may want to use "$text from list" with "," as deliminator if you start with %Lists
  2. It creates a new browser window, scrapes that window, saves to a (local) file, scrapes that local file into a table, deletes the local text file, then finally removes all additional columns from the table (called "&Matched Table").
  3. #List1 is loaded into the JavaScript object/array-of-terms.  #List2 is then matched against the 1st list.  Rows for "&Matched Table" = length of #List2.
  4. Many things can still be easily implemented in the JavaScript code.  For example, the original documentation https://github.com/Glench/fuzzyset.js/blob/master/README.rst goes into additional constraints that may be placed on the fuzzy logic.  Also, I have stripped out all but the 1st match that any single term from #List2 returns. However, all matching terms and their scores could easily be included.
  5. I have revamped the code to return "false" in the 1st Col of a row for ease of $true/$false comparisons in uBot later on. 
  6. The term "#Local Directory" is used to set a specified directory where the temporary file should be created.  Delete it if you like.

 

SOME of this code may be redundant/useless/meaningless.  If you are more knowledgeable than I, feel free to update and tighten up the code.  Point is it DOES work in uBot 5. 

 

Have fun!

Fuzzy Match Lists("alpha,bravo,charlie,Delta,Echo,biptity,bopity", "charlie,delta,echo,foxtrot,gamma")


define Fuzzy Match Lists(#List1, #List2) {
    comment("Current function takes two lists and saves results to 
\"&Matched Table\".  

Uses \"$document text\" to save page data to 
file and then load that data into &Matched Table
(as this is the only way I could figure out how to do it:)")
    comment("OUTPUT Format (&Matched Table):
0.8,testa
0.7627,testb
false
1,Found
NOTE: \'false\' is returned if no match found.")
    comment("Future Expantion Potential:
     1) deliminator choice potential
     2) include 2+ fuzzy matches
     3) can also implement the following 
          Javascript code.
          a) useLevenshtein
           gramSizeLower
          c) gramSizeUpper")
    in new browser {
        comment("NOTE: \"?Nessessary?\" pre loading of a page 
to have $document text work.")
        load html("")
        divider
        comment("**** NOTE: Replace the below w/ 
Run Javascript()
Command for stability and such. ****")
        run javascript("(function() \{

var FuzzySet = function(arr, useLevenshtein, gramSizeLower, gramSizeUpper) \{
    var fuzzyset = \{
        version: \'0.0.1\'
    \};

    // default options
    arr = arr || [];
    fuzzyset.gramSizeLower = gramSizeLower || 2;
    fuzzyset.gramSizeUpper = gramSizeUpper || 3;
    fuzzyset.useLevenshtein = useLevenshtein || true;

    // define all the object functions and attributes
    fuzzyset.exactSet = \{\};
    fuzzyset.matchDict = \{\};
    fuzzyset.items = \{\};

    // helper functions
    var levenshtein = function(str1, str2) \{
        var current = [], prev, value;

        for (var i = 0; i <= str2.length; i++)
            for (var j = 0; j <= str1.length; j++) \{
            if (i && j)
                if (str1.charAt(j - 1) === str2.charAt(i - 1))
                value = prev;
                else
                value = Math.min(current[j], current[j - 1], prev) + 1;
            else
                value = i + j;

            prev = current[j];
            current[j] = value;
            \}

        return current.pop();
    \};

    // return an edit distance from 0 to 1
    var _distance = function(str1, str2) \{
        if (str1 === null && str2 === null) throw \'Trying to compare two null values\';
        if (str1 === null || str2 === null) return 0;
        str1 = String(str1); str2 = String(str2);

        var distance = levenshtein(str1, str2);
        if (str1.length > str2.length) \{
            return 1 - distance / str1.length;
        \} else \{
            return 1 - distance / str2.length;
        \}
    \};
    var _nonWordRe = /[^\\w, ]+/;

    var _iterateGrams = function(value, gramSize) \{
        gramSize = gramSize || 2;
        var simplified = \'-\' + value.toLowerCase().replace(_nonWordRe, \'\') + \'-\',
            lenDiff = gramSize - simplified.length,
            results = [];
        if (lenDiff > 0) \{
            for (var i = 0; i < lenDiff; ++i) \{
                value += \'-\';
            \}
        \}
        for (var i = 0; i < simplified.length - gramSize + 1; ++i) \{
            results.push(simplified.slice(i, i + gramSize));
        \}
        return results;
    \};

    var _gramCounter = function(value, gramSize) \{
        // return an object where key=gram, value=number of occurrences
        gramSize = gramSize || 2;
        var result = \{\},
            grams = _iterateGrams(value, gramSize),
            i = 0;
        for (i; i < grams.length; ++i) \{
            if (grams[i] in result) \{
                result[grams[i]] += 1;
            \} else \{
                result[grams[i]] = 1;
            \}
        \}
        return result;
    \};

    // the main functions
    fuzzyset.get = function(value, defaultValue) \{
        // check for value in set, returning defaultValue or null if none found
        var result = this._get(value);
        if (!result && defaultValue) \{
            return defaultValue;
        \}
        return result;
    \};

    fuzzyset._get = function(value) \{
        var normalizedValue = this._normalizeStr(value),
            result = this.exactSet[normalizedValue];
        if (result) \{
            return [[1, result]];
        \}

        var results = [];
        // start with high gram size and if there are no results, go to lower gram sizes
        for (var gramSize = this.gramSizeUpper; gramSize >= this.gramSizeLower; --gramSize) \{
            results = this.__get(value, gramSize);
            if (results) \{
                return results;
            \}
        \}
        return null;
    \};

    fuzzyset.__get = function(value, gramSize) \{
        var normalizedValue = this._normalizeStr(value),
            matches = \{\},
            gramCounts = _gramCounter(normalizedValue, gramSize),
            items = this.items[gramSize],
            sumOfSquareGramCounts = 0,
            gram,
            gramCount,
            i,
            index,
            otherGramCount;

        for (gram in gramCounts) \{
            gramCount = gramCounts[gram];
            sumOfSquareGramCounts += Math.pow(gramCount, 2);
            if (gram in this.matchDict) \{
                for (i = 0; i < this.matchDict[gram].length; ++i) \{
                    index = this.matchDict[gram][i][0];
                    otherGramCount = this.matchDict[gram][i][1];
                    if (index in matches) \{
                        matches[index] += gramCount * otherGramCount;
                    \} else \{
                        matches[index] = gramCount * otherGramCount;
                    \}
                \}
            \}
        \}

        function isEmptyObject(obj) \{
            for(var prop in obj) \{
                if(obj.hasOwnProperty(prop))
                    return false;
            \}
            return true;
        \}

        if (isEmptyObject(matches)) \{
            return null;
        \}

        var vectorNormal = Math.sqrt(sumOfSquareGramCounts),
            results = [],
            matchScore;
        // build a results list of [score, str]
        for (var matchIndex in matches) \{
            matchScore = matches[matchIndex];
            results.push([matchScore / (vectorNormal * items[matchIndex][0]), items[matchIndex][1]]);
        \}
        var sortDescending = function(a,  \{
            if (a[0] < b[0]) \{
                return 1;
            \} else if (a[0] > b[0]) \{
                return -1;
            \} else \{
                return 0;
            \}
        \};
        results.sort(sortDescending);
        if (this.useLevenshtein) \{
            var newResults = [],
                endIndex = Math.min(50, results.length);
            // truncate somewhat arbitrarily to 50
            for (var i = 0; i < endIndex; ++i) \{
                newResults.push([_distance(results[i][1], normalizedValue), results[i][1]]);
            \}
            results = newResults;
            results.sort(sortDescending);
        \}
        var newResults = [];
        for (var i = 0; i < results.length; ++i) \{
            if (results[i][0] == results[0][0]) \{
                newResults.push([results[i][0], this.exactSet[results[i][1]]]);
            \}
        \}
        return newResults;
    \};

    fuzzyset.add = function(value) \{
        var normalizedValue = this._normalizeStr(value);
        if (normalizedValue in this.exactSet) \{
            return false;
        \}

        var i = this.gramSizeLower;
        for (i; i < this.gramSizeUpper + 1; ++i) \{
            this._add(value, i);
        \}
    \};

    fuzzyset._add = function(value, gramSize) \{
        var normalizedValue = this._normalizeStr(value),
            items = this.items[gramSize] || [],
            index = items.length;

        items.push(0);
        var gramCounts = _gramCounter(normalizedValue, gramSize),
            sumOfSquareGramCounts = 0,
            gram, gramCount;
        for (gram in gramCounts) \{
            gramCount = gramCounts[gram];
            sumOfSquareGramCounts += Math.pow(gramCount, 2);
            if (gram in this.matchDict) \{
                this.matchDict[gram].push([index, gramCount]);
            \} else \{
                this.matchDict[gram] = [[index, gramCount]];
            \}
        \}
        var vectorNormal = Math.sqrt(sumOfSquareGramCounts);
        items[index] = [vectorNormal, normalizedValue];
        this.items[gramSize] = items;
        this.exactSet[normalizedValue] = value;
    \};

    fuzzyset._normalizeStr = function(str) \{
        if (Object.prototype.toString.call(str) !== \'[object String]\') throw \'Must use a string as argument to FuzzySet functions\';
        return str.toLowerCase();
    \};

    // return length of items in set
    fuzzyset.length = function() \{
        var count = 0,
            prop;
        for (prop in this.exactSet) \{
            if (this.exactSet.hasOwnProperty(prop)) \{
                count += 1;
            \}
        \}
        return count;
    \};

    // return is set is empty
    fuzzyset.isEmpty = function() \{
        for (var prop in this.exactSet) \{
            if (this.exactSet.hasOwnProperty(prop)) \{
                return false;
            \}
        \}
        return true;
    \};

    // return list of values loaded into set
    fuzzyset.values = function() \{
        var values = [],
            prop;
        for (prop in this.exactSet) \{
            if (this.exactSet.hasOwnProperty(prop)) \{
                values.push(this.exactSet[prop]);
            \}
        \}
        return values;
    \};


    // initialization
    var i = fuzzyset.gramSizeLower;
    for (i; i < fuzzyset.gramSizeUpper + 1; ++i) \{
        fuzzyset.items[i] = [];
    \}
    // add all the items to the set
    for (i = 0; i < arr.length; ++i) \{
        fuzzyset.add(arr[i]);
    \}

    return fuzzyset;
\};

var root = this;
// Export the fuzzyset object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we\'re not in CommonJS, add `_` to the
// global object.
if (typeof module !== \'undefined\' && module.exports) \{
    module.exports = FuzzySet;
    root.FuzzySet = FuzzySet;
\} else \{
    root.FuzzySet = FuzzySet;
\}

\})();

// begining of code adapted for uBot
// Loads lists (in \"termA,termB,termC\" format)
var listA = \"{#List1}\".split(\",\");
var listB = \"{#List2}\".split(\",\");
//Initializes Data Structure FuzzyArray() with listB.
var FuzzyArray = FuzzySet(listA); 

//Runs through listB/#List2. 
//NOTE: output list will be of size listB/#List2 and 
//    in order of listB/#List2.  Null is returned if no
//    results found, to maintain a 1:1 ratio of rows
//    between JavaScript output and original #List2
//NOTE2: additional/misc. \'document.write(\"\\n\");\' are for
//    easier table formatting later on.
document.write(\"\\n\");
for (var i=0;i<listB.length;i++)\{
	document.write(FuzzyArray.get(listB[i],\"false\"));
	document.write(\",\");	// to ease formatting of table
	document.write(\"\\n\");
\}
")
        save to file("{#Local Directory}Temp Table.txt", $document text)
        create table from file("{#Local Directory}Temp Table.txt", &Matched Table)
        delete file("{#Local Directory}Temp Table.txt")
        divider
        comment("Strips out misc. HTML code from saved file
    • Cell 0,0:<html><head></head><body>***
    • Cell MaxCol,MaxRow: Column 1: ***</body></html>")
        set(#Temp Variable, $find regular expression($table cell(&Matched Table, 0, 0), "(?<=body>)[a-zA-Z0-9].*(?=)"), "Local")
        set table cell(&Matched Table, 0, 0, #Temp Variable)
        plugin command("TableCommands.dll", "delete from table", &Matched Table, "Row", $subtract($table total rows(&Matched Table), 1))
        divider
        comment("Removes all but columns 1 and 2")
        loop($subtract($table total columns(&Matched Table), 2)) {
            plugin command("TableCommands.dll", "delete from table", &Matched Table, "Column", 2)
        }
        divider
        close page
    }
}

Link to post
Share on other sites
  • 9 months later...

Apologies,

 

As an update, I realized the code above was HORRIBLY customized to my personal bot.  Here is a slightly simplified version for anyone. Keep in mind...

  • #List1 and #List2 are strings that are separated by commas
  • #list1 is the stored list.  #List2 is compared against #List1.  Note, what was confusing to me at first was that the returned string did NOT have anything from #List2 to identify which word was being compared. You will have to take this into account.  So, if List1 has 3 values and List2 has 4 values, then you will receive a string sent to"#Results" that is separated by semicolons ";" that is of length List2. 
  • Also note that, if NO match is found, you will simply find "false" between two semicolons ";", you will not have a comma in this row (see example below).
  • The comparison treats upper and lower case the same. 
  • The information that is returned is a single string which you will have to parse.  The results are returned to #List Comparison.  ";" semicolons separate rows and commas (if they exist) separates the "Levenshtein" and the term it found in #List1
  • Finally, The "Levenshtein" value is SIMILAR TO a probability of a match between 0.0 and 1.0.  The higher the probability, the higher the decimal value.  This is useful if you would like to filter out probable matches.

Again, there are more variables to change in the original code (e.g. GramSizeLower and GramSizeUpper).  Goto  http://glench.github.io/fuzzyset.js/ to find out more.

set(#List1,"alpha,bravo,charlie","Global")
set(#List2,"Charlie,Delta,Echo,YoullNeverFindThis","Global")
run javascript("(function() \{

var FuzzySet = function(arr, useLevenshtein, gramSizeLower, gramSizeUpper) \{
    var fuzzyset = \{
        version: \'0.0.1\'
    \};

    // default options
    arr = arr || [];
    fuzzyset.gramSizeLower = gramSizeLower || 2;
    fuzzyset.gramSizeUpper = gramSizeUpper || 3;
    fuzzyset.useLevenshtein = useLevenshtein || true;

    // define all the object functions and attributes
    fuzzyset.exactSet = \{\};
    fuzzyset.matchDict = \{\};
    fuzzyset.items = \{\};

    // helper functions
    var levenshtein = function(str1, str2) \{
        var current = [], prev, value;

        for (var i = 0; i <= str2.length; i++)
            for (var j = 0; j <= str1.length; j++) \{
            if (i && j)
                if (str1.charAt(j - 1) === str2.charAt(i - 1))
                value = prev;
                else
                value = Math.min(current[j], current[j - 1], prev) + 1;
            else
                value = i + j;

            prev = current[j];
            current[j] = value;
            \}

        return current.pop();
    \};

    // return an edit distance from 0 to 1
    var _distance = function(str1, str2) \{
        if (str1 === null && str2 === null) throw \'Trying to compare two null values\';
        if (str1 === null || str2 === null) return 0;
        str1 = String(str1); str2 = String(str2);

        var distance = levenshtein(str1, str2);
        if (str1.length > str2.length) \{
            return 1 - distance / str1.length;
        \} else \{
            return 1 - distance / str2.length;
        \}
    \};
    var _nonWordRe = /[^\\w, ]+/;

    var _iterateGrams = function(value, gramSize) \{
        gramSize = gramSize || 2;
        var simplified = \'-\' + value.toLowerCase().replace(_nonWordRe, \'\') + \'-\',
            lenDiff = gramSize - simplified.length,
            results = [];
        if (lenDiff > 0) \{
            for (var i = 0; i < lenDiff; ++i) \{
                value += \'-\';
            \}
        \}
        for (var i = 0; i < simplified.length - gramSize + 1; ++i) \{
            results.push(simplified.slice(i, i + gramSize));
        \}
        return results;
    \};

    var _gramCounter = function(value, gramSize) \{
        // return an object where key=gram, value=number of occurrences
        gramSize = gramSize || 2;
        var result = \{\},
            grams = _iterateGrams(value, gramSize),
            i = 0;
        for (i; i < grams.length; ++i) \{
            if (grams[i] in result) \{
                result[grams[i]] += 1;
            \} else \{
                result[grams[i]] = 1;
            \}
        \}
        return result;
    \};

    // the main functions
    fuzzyset.get = function(value, defaultValue) \{
        // check for value in set, returning defaultValue or null if none found
        var result = this._get(value);
        if (!result && defaultValue) \{
            return defaultValue;
        \}
        return result;
    \};

    fuzzyset._get = function(value) \{
        var normalizedValue = this._normalizeStr(value),
            result = this.exactSet[normalizedValue];
        if (result) \{
            return [[1, result]];
        \}

        var results = [];
        // start with high gram size and if there are no results, go to lower gram sizes
        for (var gramSize = this.gramSizeUpper; gramSize >= this.gramSizeLower; --gramSize) \{
            results = this.__get(value, gramSize);
            if (results) \{
                return results;
            \}
        \}
        return null;
    \};

    fuzzyset.__get = function(value, gramSize) \{
        var normalizedValue = this._normalizeStr(value),
            matches = \{\},
            gramCounts = _gramCounter(normalizedValue, gramSize),
            items = this.items[gramSize],
            sumOfSquareGramCounts = 0,
            gram,
            gramCount,
            i,
            index,
            otherGramCount;

        for (gram in gramCounts) \{
            gramCount = gramCounts[gram];
            sumOfSquareGramCounts += Math.pow(gramCount, 2);
            if (gram in this.matchDict) \{
                for (i = 0; i < this.matchDict[gram].length; ++i) \{
                    index = this.matchDict[gram][i][0];
                    otherGramCount = this.matchDict[gram][i][1];
                    if (index in matches) \{
                        matches[index] += gramCount * otherGramCount;
                    \} else \{
                        matches[index] = gramCount * otherGramCount;
                    \}
                \}
            \}
        \}

        function isEmptyObject(obj) \{
            for(var prop in obj) \{
                if(obj.hasOwnProperty(prop))
                    return false;
            \}
            return true;
        \}

        if (isEmptyObject(matches)) \{
            return null;
        \}

        var vectorNormal = Math.sqrt(sumOfSquareGramCounts),
            results = [],
            matchScore;
        // build a results list of [score, str]
        for (var matchIndex in matches) \{
            matchScore = matches[matchIndex];
            results.push([matchScore / (vectorNormal * items[matchIndex][0]), items[matchIndex][1]]);
        \}
        var sortDescending = function(a,  \{
            if (a[0] < b[0]) \{
                return 1;
            \} else if (a[0] > b[0]) \{
                return -1;
            \} else \{
                return 0;
            \}
        \};
        results.sort(sortDescending);
        if (this.useLevenshtein) \{
            var newResults = [],
                endIndex = Math.min(50, results.length);
            // truncate somewhat arbitrarily to 50
            for (var i = 0; i < endIndex; ++i) \{
                newResults.push([_distance(results[i][1], normalizedValue), results[i][1]]);
            \}
            results = newResults;
            results.sort(sortDescending);
        \}
        var newResults = [];
        for (var i = 0; i < results.length; ++i) \{
            if (results[i][0] == results[0][0]) \{
                newResults.push([results[i][0], this.exactSet[results[i][1]]]);
            \}
        \}
        return newResults;
    \};

    fuzzyset.add = function(value) \{
        var normalizedValue = this._normalizeStr(value);
        if (normalizedValue in this.exactSet) \{
            return false;
        \}

        var i = this.gramSizeLower;
        for (i; i < this.gramSizeUpper + 1; ++i) \{
            this._add(value, i);
        \}
    \};

    fuzzyset._add = function(value, gramSize) \{
        var normalizedValue = this._normalizeStr(value),
            items = this.items[gramSize] || [],
            index = items.length;

        items.push(0);
        var gramCounts = _gramCounter(normalizedValue, gramSize),
            sumOfSquareGramCounts = 0,
            gram, gramCount;
        for (gram in gramCounts) \{
            gramCount = gramCounts[gram];
            sumOfSquareGramCounts += Math.pow(gramCount, 2);
            if (gram in this.matchDict) \{
                this.matchDict[gram].push([index, gramCount]);
            \} else \{
                this.matchDict[gram] = [[index, gramCount]];
            \}
        \}
        var vectorNormal = Math.sqrt(sumOfSquareGramCounts);
        items[index] = [vectorNormal, normalizedValue];
        this.items[gramSize] = items;
        this.exactSet[normalizedValue] = value;
    \};

    fuzzyset._normalizeStr = function(str) \{
        if (Object.prototype.toString.call(str) !== \'[object String]\') throw \'Must use a string as argument to FuzzySet functions\';
        return str.toLowerCase();
    \};

    // return length of items in set
    fuzzyset.length = function() \{
        var count = 0,
            prop;
        for (prop in this.exactSet) \{
            if (this.exactSet.hasOwnProperty(prop)) \{
                count += 1;
            \}
        \}
        return count;
    \};

    // return is set is empty
    fuzzyset.isEmpty = function() \{
        for (var prop in this.exactSet) \{
            if (this.exactSet.hasOwnProperty(prop)) \{
                return false;
            \}
        \}
        return true;
    \};

    // return list of values loaded into set
    fuzzyset.values = function() \{
        var values = [],
            prop;
        for (prop in this.exactSet) \{
            if (this.exactSet.hasOwnProperty(prop)) \{
                values.push(this.exactSet[prop]);
            \}
        \}
        return values;
    \};


    // initialization
    var i = fuzzyset.gramSizeLower;
    for (i; i < fuzzyset.gramSizeUpper + 1; ++i) \{
        fuzzyset.items[i] = [];
    \}
    // add all the items to the set
    for (i = 0; i < arr.length; ++i) \{
        fuzzyset.add(arr[i]);
    \}

    return fuzzyset;
\};

var root = this;
// Export the fuzzyset object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we\'re not in CommonJS, add `_` to the
// global object.
if (typeof module !== \'undefined\' && module.exports) \{
    module.exports = FuzzySet;
    root.FuzzySet = FuzzySet;
\} else \{
    root.FuzzySet = FuzzySet;
\}

\})();

// begining of code adapted for uBot
// Loads lists (in \"termA,termB,termC\" format)
var listA = \"{#List1}\".split(\",\");
var listB = \"{#List2}\".split(\",\");
//Initializes Data Structure FuzzyArray() with listB.
var FuzzyArray = FuzzySet(listA); 

//Runs through listB/#List2. 
//NOTE: output list will be of size listB/#List2 and 
//    in order of listB/#List2.  Null is returned if no
//    results found, to maintain a 1:1 ratio of rows
//    between JavaScript output and original #List2
//NOTE2: additional/misc. \'document.write(\"\\n\");\' are for
//    easier table formatting later on.
document.write(\"\\n\");
var Results = \'\';
for (var i=0;i<listB.length;i++)\{
       Results += (FuzzyArray.get(listB[i],\"false\"));
	Results += \";\";	// to ease formatting of table
\}
")
set(#List Comparison,$eval("Results;"),"Global")
clear table(&Table of Matches)
add list to table as row(&Table of Matches,0,0,$list from text("List2 Elements,Levenshtein Value (false if no find),Term found in List1",","))
clear list(%Result Rows)
set(#counter,0,"Global")
add list to list(%Result Rows,$list from text(#List Comparison,";"),"Delete","Global")
loop($list total(%Result Rows)) {
    add list to table as row(&Table of Matches,$table total rows(&Table of Matches),1,$list from text($list item(%Result Rows,#counter),","))
    increment(#counter)
}
add list to table as column(&Table of Matches,1,0,$list from text(#List2,","))

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...