-
-
Notifications
You must be signed in to change notification settings - Fork 502
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add match function to Json module #1522
base: master
Are you sure you want to change the base?
Conversation
This is broader than this PR but is there a reason we favour pattern matching in the form of I've had comments from colleagues I was onboarding to fp-ts previously that match/fold is hard to understand because you don't know which callback aligns with which member of the union or sum type. It's manageable for types with fewer members like Here's a comparison in terms of readability (keeping in mind you'd usually not have the type referenced in the return value!): J.match(
() => 'null',
() => 'boolean',
() => 'number',
() => 'string',
() => 'array',
() => 'object'
)
J.match({
onNull: () => 'null',
onBoolean: () => 'boolean',
onNumber: () => 'number',
onString: () => 'string',
onArray: () => 'array',
onObject: () => 'object'
}) An additional benefit is that this lets you order the callbacks however you'd like. We could additionally experiment with how to support a universal |
I guess for verbosity's sake. I'm fine with type Err = { _type: 'NotFound', id: string } | { _type: 'SomeException', error: Error }
match({
NotFound: ({ id }) => `Resource not found with ID "${id}"`,
SomeException: ({ error }) => error.message
}) (I actually use |
Personally I'd favor the _/'otherwise' cases I would not handle at this level. But I think it would make sense to add |
Btw, I guess you have noticed the export const match: <Z>(
onNull: () => Z,
onBool: (x: boolean) => Z,
onNum: (x: number) => Z,
onStr: (x: string) => Z,
onArr: (x: JsonArray) => Z,
onObj: (x: JsonRecord) => Z
) => (j: Json) => Z = (onNull, onBool, onNum, onStr, onArr, onObj) => (j) =>
j === null
? onNull()
: typeof j === 'boolean'
? onBool(j)
: typeof j === 'number'
? onNum(j)
: typeof j === 'string'
? onStr(j)
: j instanceof Array
? onArr(j)
: onObj(j) But unfortunately this did not pass the typelevel tests for TS version 3.5 :) |
I think this may be useful to destructure Json data structures.
#1519