diff --git a/src/formatter/__test__/case.test.ts b/src/formatter/__test__/case.test.ts new file mode 100644 index 0000000..9c3d5c4 --- /dev/null +++ b/src/formatter/__test__/case.test.ts @@ -0,0 +1,21 @@ +import { switchCaseFormat } from "../case"; + +describe("switchCaseFormat", () => { + const aFieldValue = "foo"; + const switchCaseMapping = { bar: "foo", foo: "bar" }; + const anotherSwitchCaseMapping = { 1: 2, 2: 1 }; + it("should return correct mapping if fieldValue matches a case", () => { + const processor = switchCaseFormat(switchCaseMapping, ""); + expect(processor(aFieldValue)).toEqual(switchCaseMapping[aFieldValue]); + }); + + it("should return correct mapping with fieldValue type narrowing matching a case", () => { + const processor = switchCaseFormat(anotherSwitchCaseMapping, 0); + expect(processor(1)).toEqual(anotherSwitchCaseMapping[1]); + }); + + it("should return default mapping if fieldValue deos not match a case", () => { + const processor = switchCaseFormat(switchCaseMapping, ""); + expect(processor(1)).toEqual(""); + }); +}); diff --git a/src/formatter/case.ts b/src/formatter/case.ts new file mode 100644 index 0000000..3e81a90 --- /dev/null +++ b/src/formatter/case.ts @@ -0,0 +1,12 @@ +import { pipe } from "fp-ts/lib/function"; +import * as O from "fp-ts/lib/Option"; + +export const switchCaseFormat = ( + cases: { readonly [key: string]: T }, + defaultValue: T +) => (field: unknown): T => + pipe( + cases[`${field}`], + O.fromNullable, + O.getOrElse(() => defaultValue) + );