"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = group;
exports.flatGroup = flatGroup;
exports.flatRollup = flatRollup;
exports.groups = groups;
exports.index = index;
exports.indexes = indexes;
exports.rollup = rollup;
exports.rollups = rollups;

var _index = require("../../../lib-vendor/internmap/src/index.js");

var _identity = _interopRequireDefault(require("./identity.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function group(values, ...keys) {
  return nest(values, _identity.default, _identity.default, keys);
}

function groups(values, ...keys) {
  return nest(values, Array.from, _identity.default, keys);
}

function flatten(groups, keys) {
  for (let i = 1, n = keys.length; i < n; ++i) {
    groups = groups.flatMap(g => g.pop().map(([key, value]) => [...g, key, value]));
  }

  return groups;
}

function flatGroup(values, ...keys) {
  return flatten(groups(values, ...keys), keys);
}

function flatRollup(values, reduce, ...keys) {
  return flatten(rollups(values, reduce, ...keys), keys);
}

function rollup(values, reduce, ...keys) {
  return nest(values, _identity.default, reduce, keys);
}

function rollups(values, reduce, ...keys) {
  return nest(values, Array.from, reduce, keys);
}

function index(values, ...keys) {
  return nest(values, _identity.default, unique, keys);
}

function indexes(values, ...keys) {
  return nest(values, Array.from, unique, keys);
}

function unique(values) {
  if (values.length !== 1) throw new Error("duplicate key");
  return values[0];
}

function nest(values, map, reduce, keys) {
  return function regroup(values, i) {
    if (i >= keys.length) return reduce(values);
    const groups = new _index.InternMap();
    const keyof = keys[i++];
    let index = -1;

    for (const value of values) {
      const key = keyof(value, ++index, values);
      const group = groups.get(key);
      if (group) group.push(value);else groups.set(key, [value]);
    }

    for (const [key, values] of groups) {
      groups.set(key, regroup(values, i));
    }

    return map(groups);
  }(values, 0);
}