"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.values = exports.unsafeGet = exports.union = exports.some = exports.size = exports.setTree = exports.set = exports.removeMany = exports.remove = exports.reduce = exports.mutate = exports.modifyHash = exports.modifyAt = exports.modify = exports.map = exports.make = exports.keys = exports.isHashMap = exports.isEmpty = exports.hasHash = exports.hasBy = exports.has = exports.getHash = exports.get = exports.fromIterable = exports.forEach = exports.flatMap = exports.findFirst = exports.filterMap = exports.filter = exports.every = exports.entries = exports.endMutation = exports.empty = exports.countBy = exports.compact = exports.beginMutation = exports.HashMapTypeId = void 0;
var Equal = _interopRequireWildcard(require("../Equal.js"));
var _Function = _interopRequireWildcard(require("../Function.js"));
var Dual = _Function;
var Hash = _interopRequireWildcard(require("../Hash.js"));
var _Inspectable = require("../Inspectable.js");
var Option = _interopRequireWildcard(require("../Option.js"));
var _Pipeable = require("../Pipeable.js");
var _Predicate = require("../Predicate.js");
var _bitwise = require("./hashMap/bitwise.js");
var _config = require("./hashMap/config.js");
var Node = _interopRequireWildcard(require("./hashMap/node.js"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const HashMapSymbolKey = "effect/HashMap";
/** @internal */
const HashMapTypeId = exports.HashMapTypeId = /*#__PURE__*/Symbol.for(HashMapSymbolKey);
const HashMapProto = {
  [HashMapTypeId]: HashMapTypeId,
  [Symbol.iterator]() {
    return new HashMapIterator(this, (k, v) => [k, v]);
  },
  [Hash.symbol]() {
    let hash = Hash.hash(HashMapSymbolKey);
    for (const item of this) {
      hash ^= (0, _Function.pipe)(Hash.hash(item[0]), Hash.combine(Hash.hash(item[1])));
    }
    return Hash.cached(this, hash);
  },
  [Equal.symbol](that) {
    if (isHashMap(that)) {
      if (that._size !== this._size) {
        return false;
      }
      for (const item of this) {
        const elem = (0, _Function.pipe)(that, getHash(item[0], Hash.hash(item[0])));
        if (Option.isNone(elem)) {
          return false;
        } else {
          if (!Equal.equals(item[1], elem.value)) {
            return false;
          }
        }
      }
      return true;
    }
    return false;
  },
  toString() {
    return (0, _Inspectable.format)(this.toJSON());
  },
  toJSON() {
    return {
      _id: "HashMap",
      values: Array.from(this).map(_Inspectable.toJSON)
    };
  },
  [_Inspectable.NodeInspectSymbol]() {
    return this.toJSON();
  },
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
const makeImpl = (editable, edit, root, size) => {
  const map = Object.create(HashMapProto);
  map._editable = editable;
  map._edit = edit;
  map._root = root;
  map._size = size;
  return map;
};
class HashMapIterator {
  map;
  f;
  v;
  constructor(map, f) {
    this.map = map;
    this.f = f;
    this.v = visitLazy(this.map._root, this.f, undefined);
  }
  next() {
    if (Option.isNone(this.v)) {
      return {
        done: true,
        value: undefined
      };
    }
    const v0 = this.v.value;
    this.v = applyCont(v0.cont);
    return {
      done: false,
      value: v0.value
    };
  }
  [Symbol.iterator]() {
    return new HashMapIterator(this.map, this.f);
  }
}
const applyCont = cont => cont ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4]) : Option.none();
const visitLazy = (node, f, cont = undefined) => {
  switch (node._tag) {
    case "LeafNode":
      {
        if (Option.isSome(node.value)) {
          return Option.some({
            value: f(node.key, node.value.value),
            cont
          });
        }
        return applyCont(cont);
      }
    case "CollisionNode":
    case "ArrayNode":
    case "IndexedNode":
      {
        const children = node.children;
        return visitLazyChildren(children.length, children, 0, f, cont);
      }
    default:
      {
        return applyCont(cont);
      }
  }
};
const visitLazyChildren = (len, children, i, f, cont) => {
  while (i < len) {
    const child = children[i++];
    if (child && !Node.isEmptyNode(child)) {
      return visitLazy(child, f, [len, children, i, f, cont]);
    }
  }
  return applyCont(cont);
};
const _empty = /*#__PURE__*/makeImpl(false, 0, /*#__PURE__*/new Node.EmptyNode(), 0);
/** @internal */
const empty = () => _empty;
/** @internal */
exports.empty = empty;
const make = (...entries) => fromIterable(entries);
/** @internal */
exports.make = make;
const fromIterable = entries => {
  const map = beginMutation(empty());
  for (const entry of entries) {
    set(map, entry[0], entry[1]);
  }
  return endMutation(map);
};
/** @internal */
exports.fromIterable = fromIterable;
const isHashMap = u => (0, _Predicate.hasProperty)(u, HashMapTypeId);
/** @internal */
exports.isHashMap = isHashMap;
const isEmpty = self => self && Node.isEmptyNode(self._root);
/** @internal */
exports.isEmpty = isEmpty;
const get = exports.get = /*#__PURE__*/Dual.dual(2, (self, key) => getHash(self, key, Hash.hash(key)));
/** @internal */
const getHash = exports.getHash = /*#__PURE__*/Dual.dual(3, (self, key, hash) => {
  let node = self._root;
  let shift = 0;
  while (true) {
    switch (node._tag) {
      case "LeafNode":
        {
          return Equal.equals(key, node.key) ? node.value : Option.none();
        }
      case "CollisionNode":
        {
          if (hash === node.hash) {
            const children = node.children;
            for (let i = 0, len = children.length; i < len; ++i) {
              const child = children[i];
              if ("key" in child && Equal.equals(key, child.key)) {
                return child.value;
              }
            }
          }
          return Option.none();
        }
      case "IndexedNode":
        {
          const frag = (0, _bitwise.hashFragment)(shift, hash);
          const bit = (0, _bitwise.toBitmap)(frag);
          if (node.mask & bit) {
            node = node.children[(0, _bitwise.fromBitmap)(node.mask, bit)];
            shift += _config.SIZE;
            break;
          }
          return Option.none();
        }
      case "ArrayNode":
        {
          node = node.children[(0, _bitwise.hashFragment)(shift, hash)];
          if (node) {
            shift += _config.SIZE;
            break;
          }
          return Option.none();
        }
      default:
        return Option.none();
    }
  }
});
/** @internal */
const unsafeGet = exports.unsafeGet = /*#__PURE__*/Dual.dual(2, (self, key) => {
  const element = getHash(self, key, Hash.hash(key));
  if (Option.isNone(element)) {
    throw new Error("Expected map to contain key");
  }
  return element.value;
});
/** @internal */
const has = exports.has = /*#__PURE__*/Dual.dual(2, (self, key) => Option.isSome(getHash(self, key, Hash.hash(key))));
/** @internal */
const hasHash = exports.hasHash = /*#__PURE__*/Dual.dual(3, (self, key, hash) => Option.isSome(getHash(self, key, hash)));
/** @internal */
const hasBy = exports.hasBy = /*#__PURE__*/Dual.dual(2, (self, predicate) => Option.isSome(findFirst(self, predicate)));
/** @internal */
const set = exports.set = /*#__PURE__*/Dual.dual(3, (self, key, value) => modifyAt(self, key, () => Option.some(value)));
/** @internal */
const setTree = exports.setTree = /*#__PURE__*/Dual.dual(3, (self, newRoot, newSize) => {
  if (self._editable) {
    ;
    self._root = newRoot;
    self._size = newSize;
    return self;
  }
  return newRoot === self._root ? self : makeImpl(self._editable, self._edit, newRoot, newSize);
});
/** @internal */
const keys = self => new HashMapIterator(self, key => key);
/** @internal */
exports.keys = keys;
const values = self => new HashMapIterator(self, (_, value) => value);
/** @internal */
exports.values = values;
const entries = self => new HashMapIterator(self, (key, value) => [key, value]);
/** @internal */
exports.entries = entries;
const size = self => self._size;
/** @internal */
exports.size = size;
const countBy = exports.countBy = /*#__PURE__*/Dual.dual(2, (self, f) => {
  let count = 0;
  for (const [k, a] of self) {
    if (f(a, k)) {
      count++;
    }
  }
  return count;
});
/** @internal */
const beginMutation = self => makeImpl(true, self._edit + 1, self._root, self._size);
/** @internal */
exports.beginMutation = beginMutation;
const endMutation = self => {
  ;
  self._editable = false;
  return self;
};
/** @internal */
exports.endMutation = endMutation;
const mutate = exports.mutate = /*#__PURE__*/Dual.dual(2, (self, f) => {
  const transient = beginMutation(self);
  f(transient);
  return endMutation(transient);
});
/** @internal */
const modifyAt = exports.modifyAt = /*#__PURE__*/Dual.dual(3, (self, key, f) => modifyHash(self, key, Hash.hash(key), f));
/** @internal */
const modifyHash = exports.modifyHash = /*#__PURE__*/Dual.dual(4, (self, key, hash, f) => {
  const size = {
    value: self._size
  };
  const newRoot = self._root.modify(self._editable ? self._edit : NaN, 0, f, hash, key, size);
  return (0, _Function.pipe)(self, setTree(newRoot, size.value));
});
/** @internal */
const modify = exports.modify = /*#__PURE__*/Dual.dual(3, (self, key, f) => modifyAt(self, key, Option.map(f)));
/** @internal */
const union = exports.union = /*#__PURE__*/Dual.dual(2, (self, that) => {
  const result = beginMutation(self);
  forEach(that, (v, k) => set(result, k, v));
  return endMutation(result);
});
/** @internal */
const remove = exports.remove = /*#__PURE__*/Dual.dual(2, (self, key) => modifyAt(self, key, Option.none));
/** @internal */
const removeMany = exports.removeMany = /*#__PURE__*/Dual.dual(2, (self, keys) => mutate(self, map => {
  for (const key of keys) {
    remove(key)(map);
  }
}));
/**
 * Maps over the entries of the `HashMap` using the specified function.
 *
 * @since 2.0.0
 * @category mapping
 */
const map = exports.map = /*#__PURE__*/Dual.dual(2, (self, f) => reduce(self, empty(), (map, value, key) => set(map, key, f(value, key))));
/** @internal */
const flatMap = exports.flatMap = /*#__PURE__*/Dual.dual(2, (self, f) => reduce(self, empty(), (zero, value, key) => mutate(zero, map => forEach(f(value, key), (value, key) => set(map, key, value)))));
/** @internal */
const forEach = exports.forEach = /*#__PURE__*/Dual.dual(2, (self, f) => reduce(self, void 0, (_, value, key) => f(value, key)));
/** @internal */
const reduce = exports.reduce = /*#__PURE__*/Dual.dual(3, (self, zero, f) => {
  const root = self._root;
  if (root._tag === "LeafNode") {
    return Option.isSome(root.value) ? f(zero, root.value.value, root.key) : zero;
  }
  if (root._tag === "EmptyNode") {
    return zero;
  }
  const toVisit = [root.children];
  let children;
  while (children = toVisit.pop()) {
    for (let i = 0, len = children.length; i < len;) {
      const child = children[i++];
      if (child && !Node.isEmptyNode(child)) {
        if (child._tag === "LeafNode") {
          if (Option.isSome(child.value)) {
            zero = f(zero, child.value.value, child.key);
          }
        } else {
          toVisit.push(child.children);
        }
      }
    }
  }
  return zero;
});
/** @internal */
const filter = exports.filter = /*#__PURE__*/Dual.dual(2, (self, f) => mutate(empty(), map => {
  for (const [k, a] of self) {
    if (f(a, k)) {
      set(map, k, a);
    }
  }
}));
/** @internal */
const compact = self => filterMap(self, _Function.identity);
/** @internal */
exports.compact = compact;
const filterMap = exports.filterMap = /*#__PURE__*/Dual.dual(2, (self, f) => mutate(empty(), map => {
  for (const [k, a] of self) {
    const option = f(a, k);
    if (Option.isSome(option)) {
      set(map, k, option.value);
    }
  }
}));
/** @internal */
const findFirst = exports.findFirst = /*#__PURE__*/Dual.dual(2, (self, predicate) => {
  for (const ka of self) {
    if (predicate(ka[1], ka[0])) {
      return Option.some(ka);
    }
  }
  return Option.none();
});
/** @internal */
const some = exports.some = /*#__PURE__*/Dual.dual(2, (self, predicate) => {
  for (const ka of self) {
    if (predicate(ka[1], ka[0])) {
      return true;
    }
  }
  return false;
});
/** @internal */
const every = exports.every = /*#__PURE__*/Dual.dual(2, (self, predicate) => !some(self, (a, k) => !predicate(a, k)));
//# sourceMappingURL=hashMap.js.map