How to use js-combinatorics - 10 common examples

To help you get started, we’ve selected a few js-combinatorics examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oed / seedsplit / test / seedsplit.js View on Github external
function testInsufficientNumShards(shardsList, wordSeeds, numShards) {
  for (let i = 0; i < shardsList.length; i++) {
    let cmbs = Combinatorics.combination(shardsList[i], numShards)
    while (cmb = cmbs.next()) {
      let combination
      try {
        combination = seedsplit.combine(cmb)
      } catch (e) {
        // only throws when decoded hex is not valid
        assert.equal(e.message, 'Could not combine the given mnemonics')
      }
      assert.notEqual(combination, wordSeeds[i])
    }
  }
}
github boris-marinov / monad-transformers / test / permutations.js View on Github external
// This modules allows you to run nodeunit tests on all possible combinations of monads, defined in the library
var combinatorics = require('js-combinatorics')

const id = require('../lib/id')
const data = require('../lib/data')
const comp = require('../lib/comp')

const monads = [].concat([data.writer, data.list, data.maybe, id.idMinimal, id.id, id.idWrapped, comp.state, comp.reader])

const stacks = combinatorics.permutation(monads, 3).toArray()

module.exports = (stackFilter, testFunction) => stacks.filter(stackFilter).reduce((obj, stack) => {
    obj[stack.map(s => s.name).join('')] = testFunction.apply(null, stack)
    return obj
  }, {})
github chiefsmurph / robinhood-playground / analysis / smart-pms.js View on Github external
console.log(JSON.stringify(pmCache, null, 2));

    // for each day
    // sort list of pm's ordered
    // pmList: [

    // console.log(Object.keys(pmCache))
    const daysVals = [];

    const pms = Object.keys(pmCache);
    // console.log(pms, numChunks)
    if (Number(numChunks) > pms.length) {
        return null;
    }
    const cmb = Combinatorics.bigCombination(pms, Number(numChunks));
    while (a = cmb.next()) {
        console.log(a);
        const trends = filesOfInterest.map(day => {
            return a.map(pm => pmCache[pm][day]);
        });
        const avgTrends = trends.map(ts => avgArray(ts.filter(val => !!val)))
        const avgOfAvgs = avgArray(avgTrends.filter(val => !!val));
        daysVals.push({
            pmList: a,
            trends,
            avgTrends,
            avgOfAvgs
        });
    }

    // console.log(JSON.stringify(daysVals, null, 2));
github 0xProject / 0x-monorepo / contracts / exchange / src / balance_stores / blockchain_balance_store.ts View on Github external
public async updateErc1155BalancesAsync(): Promise {
        const erc1155ContractsByAddress = _.zipObject(
            this._tokenContracts.erc1155.map(contract => contract.address),
            this._tokenContracts.erc1155,
        );

        for (const [tokenAddress, { fungible, nonFungible }] of Object.entries(this._tokenIds.erc1155)) {
            const contract = erc1155ContractsByAddress[tokenAddress];
            const tokenIds = [...fungible, ...nonFungible];
            if (this._ownerAddresses.length === 0 || tokenIds.length === 0) {
                continue;
            }

            const [_tokenIds, _tokenOwners] = _.unzip(
                combinatorics.cartesianProduct(tokenIds, this._ownerAddresses).toArray(),
            );
            const balances = await contract
                .balanceOfBatch(_tokenOwners as string[], _tokenIds as BigNumber[])
                .callAsync();

            let i = 0;
            for (const tokenOwner of this._ownerAddresses) {
                // Fungible tokens
                _.set(this.balances.erc1155, [tokenOwner, tokenAddress, 'fungible'], {});
                for (const tokenId of fungible) {
                    _.set(
                        this.balances.erc1155,
                        [tokenOwner, tokenAddress, 'fungible', tokenId.toString()],
                        balances[i++],
                    );
                }
github mattapperson / patronus / lib / internalUse.js View on Github external
optional = optional.concat(params.filter(function (param) {

                    // tag the param type so we know what we are looking at later
                    // We must do this becuase to get a truly random combo we must
                    // have a flat array of all param types
                    param.paramType = validation;

                    // Filter for just the optional param combos
                    return !param.flags || !param.flags.required;
                }));

            }
        });

        // OK, now we get all the mix and matched combos, and append required params to each combo
        combos = combinatorics.power(optional).map(function (combo) {

            if (combo.length < 1) {
                combo.push({});
            }
            // add the required params to each combo
            return combo.concat(required);
        });

        // Transform the flat array into an array of objects, where there is a key for each type
        returnedCombos = combos.map(function (combo) {
            var object = {};
            var paramType;

            combo.forEach(function (param) {

                paramType = param.paramType;
github namshi / mockserver / mockserver.js View on Github external
header = header.toLowerCase();
          if (req.headers[header]) {
            headers.push(
              '_' + normalizeHeader(header) + '=' + req.headers[header]
            );
          }
        });
      }

      // Now, permute the possible headers, and look for any matching files, prioritizing on
      // both # of headers and the original header order
      let matched,
        permutations = [[]];

      if (headers.length) {
        permutations = Combinatorics.permutationCombination(headers)
          .toArray()
          .sort(function(a, b) {
            return b.length - a.length;
          });
        permutations.push([]);
      }

      matched = getContentFromPermutations(
        path,
        method,
        body,
        query,
        permutations.slice(0)
      );

      if (!matched.content && (path = getWildcardPath(path))) {
github kengz / Risk-game / main.js View on Github external
// The main class that runs arena multiple times and export for analysis

// dependencies
var cmb = require('js-combinatorics').Combinatorics;
var _ = require('underscore');
var fs = require('fs');

// For configs
// var ps = require('./srcdata/filtered-AI-personalities.json');
var ps = require('./srcdata/AI-personalities.json');
var pls = ['p0','p1','p2'];
// The max turn for a game
var max = 300;

// The game constructor from arena
var game = require('./arena.js').Game;

// repeat games for a fixed config: personalities, player order.
function repeat(n, c, o) {
	// the game-series
github DefinitelyTyped / DefinitelyTyped / js-combinatorics / js-combinatorics-tests.ts View on Github external
const filteredbaseNs:string[][] = baseN.filter((i:string[]) => i.length > 0);
const allbaseNs:string[][] = baseN.toArray();
const baseNsCount = baseN.length;
const nthbaseN:string[] = baseN.nth(3);

const cartesianProduct1 = Combinatorics.cartesianProduct(["a", "b", "c"]);
const nextCartesianProduct1:[string] = cartesianProduct1.next();
cartesianProduct1.forEach((i:[string]) => console.log(i));
const cartesianProduct1sLengths:number[] = cartesianProduct1.map((i:[string]) => i.length);
const filteredCartesianProduct1s:[string][] = cartesianProduct1.filter((i:[string]) => i.length > 0);
const allCartesianProduct1s:[string][] = cartesianProduct1.toArray();
const cartesianProduct1sCount = cartesianProduct1.length;
const nthCartesianProduct1:[string] = cartesianProduct1.nth(3);
const cartesianProduct1ByCoords:[string] = cartesianProduct1.get(1);

const cartesianProduct2 = Combinatorics.cartesianProduct(["a", "b", "c"], [1, 2, 3]);
const nextCartesianProduct2:[string, number] = cartesianProduct2.next();
cartesianProduct2.forEach((i:[string, number]) => console.log(i));
const cartesianProduct2sLengths:number[] = cartesianProduct2.map((i:[string, number]) => i.length);
const filteredCartesianProduct2s:[string, number][] = cartesianProduct2.filter((i:[string, number]) => i.length > 0);
const allCartesianProduct2s:[string, number][] = cartesianProduct2.toArray();
const cartesianProduct2sCount = cartesianProduct2.length;
const nthCartesianProduct2:[string, number] = cartesianProduct2.nth(3);
const cartesianProduct2ByCoords:[string, number] = cartesianProduct2.get(1, 1);

const cartesianProduct3 = Combinatorics.cartesianProduct(["a", "b", "c"], [1, 2, 3], [true, false]);
const nextCartesianProduct3:[string, number, boolean] = cartesianProduct3.next();
cartesianProduct3.forEach((i:[string, number, boolean]) => console.log(i));
const cartesianProduct3sLengths:number[] = cartesianProduct3.map((i:[string, number, boolean]) => i.length);
const filteredCartesianProduct3s:[string, number, boolean][] = cartesianProduct3.filter((i:[string, number, boolean]) => i.length > 0);
const allCartesianProduct3s:[string, number, boolean][] = cartesianProduct3.toArray();
const cartesianProduct3sCount = cartesianProduct3.length;
github DefinitelyTyped / DefinitelyTyped / js-combinatorics / js-combinatorics-tests.ts View on Github external
const allCartesianProduct1s:[string][] = cartesianProduct1.toArray();
const cartesianProduct1sCount = cartesianProduct1.length;
const nthCartesianProduct1:[string] = cartesianProduct1.nth(3);
const cartesianProduct1ByCoords:[string] = cartesianProduct1.get(1);

const cartesianProduct2 = Combinatorics.cartesianProduct(["a", "b", "c"], [1, 2, 3]);
const nextCartesianProduct2:[string, number] = cartesianProduct2.next();
cartesianProduct2.forEach((i:[string, number]) => console.log(i));
const cartesianProduct2sLengths:number[] = cartesianProduct2.map((i:[string, number]) => i.length);
const filteredCartesianProduct2s:[string, number][] = cartesianProduct2.filter((i:[string, number]) => i.length > 0);
const allCartesianProduct2s:[string, number][] = cartesianProduct2.toArray();
const cartesianProduct2sCount = cartesianProduct2.length;
const nthCartesianProduct2:[string, number] = cartesianProduct2.nth(3);
const cartesianProduct2ByCoords:[string, number] = cartesianProduct2.get(1, 1);

const cartesianProduct3 = Combinatorics.cartesianProduct(["a", "b", "c"], [1, 2, 3], [true, false]);
const nextCartesianProduct3:[string, number, boolean] = cartesianProduct3.next();
cartesianProduct3.forEach((i:[string, number, boolean]) => console.log(i));
const cartesianProduct3sLengths:number[] = cartesianProduct3.map((i:[string, number, boolean]) => i.length);
const filteredCartesianProduct3s:[string, number, boolean][] = cartesianProduct3.filter((i:[string, number, boolean]) => i.length > 0);
const allCartesianProduct3s:[string, number, boolean][] = cartesianProduct3.toArray();
const cartesianProduct3sCount = cartesianProduct3.length;
const nthCartesianProduct3:[string, number, boolean] = cartesianProduct3.nth(3);
const cartesianProduct3ByCoords:[string, number, boolean] = cartesianProduct3.get(1, 1);

const cartesianProductAny = Combinatorics.cartesianProduct(["a", 1, true], [false, 2, "b"]);
const nextCartesianProductAny:any[] = cartesianProductAny.next();
cartesianProductAny.forEach((i:any[]) => console.log(i));
const cartesianProductAnysLengths:number[] = cartesianProductAny.map((i:any[]) => i.length);
const filteredCartesianProductAnys:any[][] = cartesianProductAny.filter((i:any[]) => i.length > 0);
const allCartesianProductAnys:any[][] = cartesianProductAny.toArray();
const cartesianProductAnysCount = cartesianProductAny.length;
github 0xProject / 0x-monorepo / contracts / test-utils / src / combinatorial_utils.ts View on Github external
export function testCombinatoriallyWithReferenceFunc(
    name: string,
    referenceFuncAsync: (...args: any[]) => Promise,
    testFuncAsync: (...args: any[]) => Promise,
    allValues: any[],
): void {
    const testCases = combinatorics.cartesianProduct(...allValues);
    let counter = 0;
    testCases.forEach(async testCase => {
        counter += 1;
        it(`${name} ${counter}/${testCases.length}`, async () => {
            await testWithReferenceFuncAsync(referenceFuncAsync, testFuncAsync, testCase as any);
        });
    });
}