@redu/

Combinations Benchmark

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Array.prototype.combinationsA = function(n){
  return this.reduce((p,c,i,a) => (Array.prototype.push.apply(p,n > 1 ? a.slice(i+1).combinationsA(n-1).map(e => (e.push(c),e))
                                                                      : [[c]]),p),[]);
};

Array.prototype.combinationsB = function(n){
  return this.reduce((p,c,i,a) => p.concat(n > 1 ? a.slice(i+1).combinationsB(n-1).map(e => (e.push(c),e))
                                                 : [[c]]),[]);
};

function combinationsC(a,n){
  var sa;
  return a.reduce(function(p,c,i,a){
                    if (n > 1) sa = combinationsC(a.slice(i+1), n-1).map(e => (e.push(c),e));
                    else sa = [[c]];
                    return p.concat(sa);
                  },[]);
}

var arr = Array(30).fill().map((_,i) => i ),
     ps = 0,
     pe = 0,
    res = [];

//console.log(arr);

ps = performance.now();
res = arr.combinationsA(6);
pe = performance.now();
console.log("with push done in:", pe-ps, res.length);

ps = performance.now();
res = arr.combinationsB(6);
pe = performance.now();
console.log("with concat done in:", pe-ps, res.length);

ps = performance.now();
res = combinationsC(arr,6);
pe = performance.now();
console.log("with concat done in:", pe-ps, res.length);
Native Browser JavaScript