import { Promised } from "./functions/utils";

export function FakeHash<T>(comparitor: (a: T, b: T) => boolean) {
  let entries: T[] = [];
  return {
    add(item: T) {
      entries = [...entries, item];
    },
    remove(item: T) {
      entries = entries.filter((e) => !comparitor(e, item));
    },
    contains(item: T) {
      return entries.find((e) => comparitor(e, item)) != null;
    },
  };
}

export function FakeAsyncHash<T>(
  comparitor: (a: T, b: T) => Promised<boolean>
) {
  let entries: T[] = [];
  return {
    add(item: T) {
      entries = [...entries, item];
    },
    async remove(item: T) {
      const next = [];
      for (const entry of entries) {
        if (!(await Promise.resolve(comparitor(entry, item)))) next.push(entry);
      }

      entries = next;
    },
    async contains(item: T) {
      for (const entry of entries) {
        if (await Promise.resolve(comparitor(entry, item))) return true;
      }

      return false;
    },
  };
}
