Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 1784

How can I implement Order from Effect-ts

$
0
0

Need help translating this typescript code:

export type Order<T> = (a: T, b: T) => -1 | 0 | 1;

export const make =
  <T>(compare: Order<T>) =>
  (self: T, other: T) =>
    self === other ? 0 : compare(self, other);

export const str: Order<string> = make((a, b) =>
  a.localeCompare(b) > 0 ? 1 : -1
);

export const num: Order<number> = make((a, b) => (a > b ? 1 : -1));

export const bool: Order<boolean> = make((a, _b) => (a === false ? -1 : 1));

export const date: Order<Date> = make((a, b) => {
  const aTime = a.getTime();
  const bTime = b.getTime();
  if (aTime === bTime) return 0;
  return aTime < bTime ? -1 : 1;
});

export const map = <T, U>(order: Order<T>, getter: (self: U) => T) =>
  make<U>((self, other) => order(getter(self), getter(other)));

export const combine = <T>(...orders: [Order<T>, ...Array<Order<T>>]) =>
  make<T>((a, b) => {
    for (const order of orders) {
      const out = order(a, b);
      if (out !== 0) return out;
    }
    return 0;
  });

export const reverse = <T>(order: Order<T>): Order<T> =>
  make((a, b) => order(b, a));

If there is any other way to achieve this kind of composability, please share.


Viewing all articles
Browse latest Browse all 1784

Trending Articles