Skip to content

Commit

Permalink
feat(constraints): add util constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
lparolari committed Oct 14, 2020
1 parent 466ca92 commit caf2cc8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/__tests__/constraint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import moment, { Moment } from "moment";

import { eq, ge, gt, le, lt, ne } from "../constraint";
import { addInterval } from "../util";

describe("comparison constraints", () => {
const c = moment();
const equal = c;
const greater = addInterval({ amount: 1, unit: "hour" })(c);
const less = addInterval({ amount: -1, unit: "hour" })(c);

const injectCurrent = (f: (c: Moment) => boolean): boolean => f(c);

test("lt", () => {
expect(injectCurrent(lt(equal))).toBe(false);
expect(injectCurrent(lt(greater))).toBe(true);
expect(injectCurrent(lt(less))).toBe(false);
});

test("le", () => {
expect(injectCurrent(le(equal))).toBe(true);
expect(injectCurrent(le(greater))).toBe(true);
expect(injectCurrent(le(less))).toBe(false);
});

test("eq", () => {
expect(injectCurrent(eq(equal))).toBe(true);
expect(injectCurrent(eq(greater))).toBe(false);
expect(injectCurrent(eq(less))).toBe(false);
});

test("ne", () => {
expect(injectCurrent(ne(equal))).toBe(false);
expect(injectCurrent(ne(greater))).toBe(true);
expect(injectCurrent(ne(less))).toBe(true);
});

test("ge", () => {
expect(injectCurrent(ge(equal))).toBe(true);
expect(injectCurrent(ge(greater))).toBe(false);
expect(injectCurrent(ge(less))).toBe(true);
});

test("gt", () => {
expect(injectCurrent(gt(equal))).toBe(false);
expect(injectCurrent(gt(greater))).toBe(false);
expect(injectCurrent(gt(less))).toBe(true);
});
});
7 changes: 7 additions & 0 deletions src/constraint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,10 @@ export type Constraint = (current: Moment) => boolean;

export const validate = (constraints: Constraint[]) => (current: Moment) =>
R.all(R.identity, R.map(R.applyTo(current), constraints));

export const gt = (threshold: Moment) => (current: Moment): boolean => current.isAfter(threshold); // c > t
export const ge = (threshold: Moment) => (current: Moment): boolean => current.isSameOrAfter(threshold); // c >= t
export const eq = (threshold: Moment) => (current: Moment): boolean => current.isSame(threshold); // c == t
export const ne = (threshold: Moment) => (current: Moment): boolean => !current.isSame(threshold); // c != t
export const le = (threshold: Moment) => (current: Moment): boolean => current.isSameOrBefore(threshold); // c <= t
export const lt = (threshold: Moment) => (current: Moment): boolean => current.isBefore(threshold); // c < t

0 comments on commit caf2cc8

Please sign in to comment.