Skip to content

Commit

Permalink
Add fold function
Browse files Browse the repository at this point in the history
  • Loading branch information
fboeller committed Mar 8, 2021
1 parent c7c5d2b commit d8ca804
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { errored, idle, loaded, loading } from '../loadable.constructors';
import { Loadable } from '../loadable.type';
import { fold } from './fold.function';

describe('the fold function', () => {
const constructors = {
idle: () => 2,
loading: () => 3,
loaded: (v: number) => v * 2,
error: (_e: unknown) => 0,
};

it.each([
[idle, 2],
[loading, 3],
[loaded(5), 10],
[errored('error'), 0],
])(
'returns for the loadable %s the value %s',
(loadable: Loadable<number>, expectation: number) => {
expect(fold(constructors, loadable)).toEqual(expectation);
}
);
});
22 changes: 22 additions & 0 deletions projects/ngx-loading-customizer/src/lib/functions/fold.function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { hasErrored, isIdle, isLoaded } from '../loadable.functions';
import { Loadable } from '../loadable.type';

export function fold<T, S>(
constructors: {
idle: () => S;
loading: () => S;
loaded: (value: T) => S;
error: (error: unknown) => S;
},
loadable: Loadable<T>
): S {
if (isLoaded(loadable)) {
return constructors.loaded(loadable.value);
} else if (hasErrored(loadable)) {
return constructors.error(loadable.error);
} else if (isIdle(loadable)) {
return constructors.idle();
} else {
return constructors.loading();
}
}

0 comments on commit d8ca804

Please sign in to comment.