functional/comparison.test.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-05-13 09:46:10 +00:00
import { expect, test } from "./deps.test.ts";
2020-05-11 22:34:57 +00:00
import { bool, cmp, is } from "./comparison.ts";
2020-05-13 09:46:10 +00:00
test("cmp", () => {
expect([8, 3, 5].sort(cmp())).toEqual([3, 5, 8]);
expect([8, 3, 5, 8].sort(cmp({ reverse: true }))).toEqual([8, 8, 5, 3]);
expect([-2, 8, -7].sort(cmp({ key: Math.abs }))).toEqual([-2, -7, 8]);
expect(["c", "a", "b"].sort(cmp())).toEqual(["a", "b", "c"]);
2020-05-11 22:34:57 +00:00
});
2020-05-13 09:46:10 +00:00
test("is", () => {
2020-05-11 22:34:57 +00:00
const f1 = is(5);
2020-05-13 09:46:10 +00:00
expect(f1(5)).toBe(true);
expect(f1(4)).toBe(false);
expect(f1("a" as any)).toBe(false);
expect(f1(null as any)).toBe(false);
expect(f1(undefined as any)).toBe(false);
2020-05-11 22:34:57 +00:00
const obj: { x: number } = { x: 1 };
let f2 = is(obj);
2020-05-13 09:46:10 +00:00
expect(f2(obj)).toBe(true);
expect(f2({ x: 1 })).toBe(false);
expect(f2({ y: 1 } as any)).toBe(false);
2020-05-11 22:34:57 +00:00
});
2020-05-13 09:46:10 +00:00
test("bool", () => {
expect(bool(null)).toBe(false);
expect(bool(undefined)).toBe(false);
2020-05-11 22:34:57 +00:00
2020-05-13 09:46:10 +00:00
expect(bool(false)).toBe(false);
expect(bool(true)).toBe(true);
2020-05-11 22:34:57 +00:00
2020-05-13 09:46:10 +00:00
expect(bool(-1)).toBe(true);
expect(bool(0)).toBe(false);
expect(bool(1)).toBe(true);
2020-05-11 22:34:57 +00:00
2020-05-13 09:46:10 +00:00
expect(bool("")).toBe(false);
expect(bool(" ")).toBe(true);
expect(bool("abc")).toBe(true);
2020-05-11 22:34:57 +00:00
2020-05-13 09:46:10 +00:00
expect(bool([])).toBe(false);
expect(bool([0])).toBe(true);
expect(bool([1, 2, 3])).toBe(true);
2020-05-11 22:34:57 +00:00
2020-05-13 09:46:10 +00:00
expect(bool(new Set())).toBe(false);
expect(bool(new Set([0]))).toBe(true);
expect(bool(new Set([1, 2, 3]))).toBe(true);
2020-05-11 22:34:57 +00:00
2020-05-13 09:46:10 +00:00
expect(bool({})).toBe(false);
expect(bool({ a: 5 })).toBe(true);
2020-05-11 22:34:57 +00:00
class Obj1 {}
class Obj2 {
private x = 0;
}
2020-05-13 09:46:10 +00:00
expect(bool(new Obj1())).toBe(false);
expect(bool(new Obj2())).toBe(true);
2020-05-11 22:34:57 +00:00
});