Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good mathematical sets implementation in JavaScript?

Where is a good mathematical sets implementation for JavaScript? It should include efficient implementations of intersection, union, complement, and (for bonus points) the Cartesian product.

No, it's not homework. I got a yubikey, it is a USB keyboard that types a sequence chosen from 16 keycodes to type a 128-bit one time password (otp). To make it more useful, software should detect the keyboard layout based on the characters produced and map those characters back to what they would be in the "us" layout for compatibility with the existing backend.

So I've got 93 different sequences of 16 characters representing everything the yubikey can type in each of 430 keyboard layouts. (Many layouts are the same for this purpose.) The possible mappings for a particular otp is each 16-character sequence that contains every character in the otp.

To find this efficiently I use a reverse index mapping each possible character to a list of the keyboard layouts that use that character. The answer is the intersection of each entry of the reverse index for each unique character in the otp. This almost always winds up with exactly 1 element.

It would be easier to write this cross-browser with a good implementation of Set().

Code so far is at http://dingoskidneys.com/~dholth/yubikey/

like image 298
joeforker Avatar asked Nov 30 '22 06:11

joeforker


1 Answers

By using jPaq or another JavaScript library that implements the Array.prototype.reduce and Array.prototype.forEach functions, you can create a cartesian product function that accepts two or more arrays. Here is code for a function that computes the cartesian product of two or more arrays:

function cartesianProductOf() {
  return Array.prototype.reduce.call(arguments, function(a, b) {
    var ret = [];
    a.forEach(function(a) {
      b.forEach(function(b) {
        ret.push(a.concat([b]));
      });
    });
    return ret;
  }, [[]]);
}

As far as this being in a library, I am open to suggestions for the naming of the function so that I can add it into jPaq. By the way, so as not to plagiarize, I did get the idea of using reduce from this post.

like image 193
Chris West Avatar answered Dec 09 '22 19:12

Chris West