Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/Json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,48 @@ export const parse = (s: string): Either<unknown, Json> => parseJSON(s, identity
*/
// tslint:disable-next-line: deprecation
export const stringify = <A>(a: A): Either<unknown, string> => stringifyJSON(a, identity)

// -----------------------------------------------------------------------------
// destructors
// -----------------------------------------------------------------------------

/**
* Takes a function for each possible Json type and returns the result of the one from the position that matches the given data.
*
* @category destructors
* @example
* import * as J from 'fp-ts/Json'
*
* const typeOf = J.match(
* () => 'null',
* () => 'boolean',
* () => 'number',
* () => 'string',
* () => 'array',
* () => 'object'
* )
*
* assert.deepStrictEqual(typeOf(32.2), 'number')
* assert.deepStrictEqual(typeOf(['a', 'b']), 'array')
*
* @since 2.10.6
*/
export const match: <Z>(
isNull: () => Z,
isBool: (x: boolean) => Z,
isNum: (x: number) => Z,
isStr: (x: string) => Z,
isArr: (x: Array<Json>) => Z,
isObj: (x: Record<string, Json>) => Z
) => (j: Json) => Z = (isNull, isBool, isNum, isStr, isArr, isObj) => (j) =>
j === null
? isNull()
: typeof j === 'boolean'
? isBool(j)
: typeof j === 'number'
? isNum(j)
: typeof j === 'string'
? isStr(j)
: Array.isArray(j)
? isArr(j)
: isObj(j as JsonRecord)
11 changes: 11 additions & 0 deletions test/Json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,15 @@ describe('Json', () => {

U.deepStrictEqual(_.stringify(undefined as any), E.left(new Error('Converting unsupported structure to JSON')))
})

it('match', () => {
const t = () => true
const f = () => false
U.strictEqual(_.match(t, f, f, f, f, f)(null), true)
U.strictEqual(_.match(f, t, f, f, f, f)(true), true)
U.strictEqual(_.match(f, f, t, f, f, f)(32.2), true)
U.strictEqual(_.match(f, f, f, t, f, f)('dolphin'), true)
U.strictEqual(_.match(f, f, f, f, t, f)(['zebra', 'tiger']), true)
U.strictEqual(_.match(f, f, f, f, f, t)({ name: 'Toni', age: 35 }), true)
})
})