js-combinatorics
Version:
Simple combinatorics like power set, combination, and permutation in JavaScript
190 lines (182 loc) • 4.35 kB
JavaScript
/*
* use mocha to test me
* http://visionmedia.github.com/mocha/
*/
var assert, Combinatorics;
if (this['window'] !== this) {
assert = require("assert");
Combinatorics = require('../.');
}
var is_deeply = function (a, e, m) {
return function () {
assert.equal(JSON.stringify(a), JSON.stringify(e), m)
}
};
var IT=function(t,f){it(JSON.stringify(t),f)}; // mocha 3
describe('Combinatorics.cartesianProduct', function () {
var c = Combinatorics.cartesianProduct(
[], [0, 10, 20], [0, 100, 200]);
IT(c.toArray(), is_deeply(c.toArray(), [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]
]));
IT(0 + c, is_deeply(0 + c, c.toArray().length));
IT(c.length, is_deeply(c.length, c.toArray().length));
IT(c.toArray(), is_deeply(c.filter(function (a) {
return a[0] === 0
}), [
[],
[],
[],
[],
[],
[],
[],
[],
[]
]));
// Testing lazy filter
c = Combinatorics.cartesianProduct(
[], [0, 10, 20], [0, 100, 200]).lazyFilter(function(a){
return a[0] === 0
});
IT(c.toArray(), is_deeply(c.toArray(), [
[],
[],
[],
[],
[],
[],
[],
[],
[]
]));
// And resetting the lazy filter
c.lazyFilter();
IT(c.toArray(), is_deeply(c.toArray(), [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]
]));
// Testing lazy map
c = Combinatorics.cartesianProduct(
[], [0, 10, 20], [0, 100, 200]).lazyMap(function(a){
if (a[0] === 2) {
a[0] = 3
}
return a;
});
IT(c.toArray(), is_deeply(c.toArray(), [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]
]));
// And resetting the lazy map
c.lazyMap();
IT(c.toArray(), is_deeply(c.toArray(), [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]
]));
// Testing .reduce
var r = function(a, e, i){return a + i + ":" + e + ";"};
var s = c.toArray().reduce(r, "");
IT( s + " // c.reduce", is_deeply(s, c.reduce(r, "")));
});