Skip to content

Instantly share code, notes, and snippets.

@jessekelly881
Last active May 17, 2024 13:11
Show Gist options
  • Select an option

  • Save jessekelly881/27782d648612c3296896a84d3bcd89c8 to your computer and use it in GitHub Desktop.

Select an option

Save jessekelly881/27782d648612c3296896a84d3bcd89c8 to your computer and use it in GitHub Desktop.
Schema optionalTextProp
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" });
});
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