Last active
May 17, 2024 13:11
-
-
Save jessekelly881/27782d648612c3296896a84d3bcd89c8 to your computer and use it in GitHub Desktop.
Schema optionalTextProp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| it("optionalTextProp", (ctx) => { | |
| const schema = Schema.Struct({ | |
| text: SchemaUtils.optionalTextProp(Schema.String) | |
| }); | |
| const decode = Schema.decodeSync(schema); | |
| const encode = Schema.encodeSync(schema); | |
| ctx.expect(decode({})).toEqual({ text: Option.none() }); | |
| ctx.expect(decode({ text: "" })).toEqual({ text: Option.none() }); | |
| ctx.expect(decode({ text: " " })).toEqual({ text: Option.none() }); | |
| ctx.expect(decode({ text: null })).toEqual({ text: Option.none() }); | |
| ctx.expect(decode({ text: "a" })).toEqual({ text: Option.some("a") }); | |
| ctx.expect(decode({ text: " a " })).toEqual({ text: Option.some("a") }); | |
| ctx.expect(encode({ text: Option.none() })).toEqual({}); | |
| ctx.expect(encode({ text: Option.some("") })).toEqual({}); | |
| ctx.expect(encode({ text: Option.some(" ") })).toEqual({}); | |
| ctx.expect(encode({ text: Option.some("a") })).toEqual({ text: "a" }); | |
| ctx.expect(encode({ text: Option.some(" a ") })).toEqual({ text: "a" }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fromString = (s: string): Option.Option<string> => | |
| s.trim() === "" ? Option.none() : Option.some(s); | |
| /** | |
| * A string prop that is truncated and omited when text is empty. | |
| * Used for descriptions where an empty value or only whitespace should be ignored. | |
| * @since 1.0.0 | |
| */ | |
| export const optionalTextProp = <R>(s: Schema.Schema<string, string, R>) => | |
| Schema.optionalToRequired(Schema.Union(s, Schema.Null), Schema.OptionFromSelf(s), { | |
| decode: (s) => | |
| Option.flatMap( | |
| Option.flatMap(s, (val) => | |
| Option.fromNullable(val ? String.trim(val) : val) | |
| ), | |
| fromString | |
| ), | |
| encode: (s) => | |
| Option.flatMap(Option.map(s, String.trim), fromString) | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment