summaryrefslogtreecommitdiff
path: root/tst/optional.test.ts
blob: ece6b3155334c95051674377f47576159708d454 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { IOptionalEmptyError, Optional, isOptional } from '../lib/index';

describe('types/fn/optional', () => {
    test('from creates some/none', () => {
        expect(Optional.from('x').get()).toBe('x');
        expect(Optional.from(null).present()).toBe(false);
        expect(Optional.from(undefined).present()).toBe(false);
    });

    test('get throws on none', () => {
        expect(() => Optional.none().get()).toThrow(IOptionalEmptyError);
    });

    test('map/filter/flatMap work', () => {
        const res = Optional.from(2)
            .map((n: number) => n * 2)
            .filter((n: number) => n > 3)
            .flatMap((n: number) => Optional.from(n.toString()));

        expect(res.get()).toBe('4');
    });

    test('orSome supplies fallback', () => {
        const res = Optional.none<number>().orSome(() => 5);
        expect(res.get()).toBe(5);
    });

    test('iterator yields only when present', () => {
        expect(Array.from(Optional.some(1))).toEqual([1]);
        expect(Array.from(Optional.none<number>())).toEqual([]);
    });

    test('isOptional detects tagged values', () => {
        expect(isOptional(Optional.some('x'))).toBe(true);
        expect(isOptional({})).toBe(false);
    });
});