What's a good mathematical sets implementation in JavaScript?

前端 未结 7 1391
予麋鹿
予麋鹿 2021-02-06 16:19

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

相关标签:
7条回答
  • 2021-02-06 16:35

    Using Underscore's reduce method.

    function cartesianProductOf(){
        return _.reduce(arguments, function(mtrx, vals){
            return _.reduce(vals, function(array, val){
                return array.concat(
                    _.map(mtrx, function(row){ return row.concat(val); })
                );
            }, []);
        }, [[]]);
    }
    
    0 讨论(0)
  • 2021-02-06 16:37

    I've done a JavaScript Set implementation mainly concerned with efficient difference, intersection and union operations. It's available at GitHub. Forks and new operations are very welcome! :-)

    0 讨论(0)
  • 2021-02-06 16:39

    Sylvester is a good library for doing vector and matrix Math in Javascript. It's the only Math library I can think of right now.

    0 讨论(0)
  • 2021-02-06 16:39

    In the program that sparked this question, a set is an Array and intersect is

    s = [1,2,3];
    q = [3,4,5];
    sq = s.filter(function(x) {
        return q.indexOf(x) >= 0;
    });
    

    Of course it doesn't work in ie.

    0 讨论(0)
  • 2021-02-06 16:43

    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.

    0 讨论(0)
  • 2021-02-06 16:48

    I personally like how it is done in jPaq (http://jpaq.org/documentation/Arrays+as+Sets/1.0/). Here are three examples that I tested out successfully:

    alert([1,2,3,4,5].subtract([2,3,5]));  // evaluates to [1,4]
    alert([1,2,5].union([1,3,4,5]));  // evaluates to [1,2,5,3,4]
    alert([1,2,3,5].intersect([0,1,2,4,6]));  // evaluates to [1,2]
    

    The nice thing about jPaq is the fact that you can just download the code for these three functions. jPaq makes it so you don't have to download the extra stuff that you will not be using anyway.

    0 讨论(0)
提交回复
热议问题