remeda
Version:
A utility library for JavaScript and Typescript.
1 lines • 2.8 kB
Source Map (JSON)
{"version":3,"file":"defaultTo.cjs","names":["purry"],"sources":["../src/defaultTo.ts"],"sourcesContent":["import type { IsEqual } from \"type-fest\";\nimport { purry } from \"./purry\";\nimport type { RemedaTypeError } from \"./internal/types/RemedaTypeError\";\n\ntype FallbackOf<T> =\n IsEqual<T, NonNullable<T>> extends true\n ? RemedaTypeError<\n \"defaultTo\",\n \"no unnecessary fallback\",\n // The type is `never` because it will never be used ;)\n { type: never; metadata: T }\n >\n : T;\n\n/**\n * A stricter wrapper around the [Nullish coalescing operator `??`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)\n * that ensures that the fallback matches the type of the data. Only works\n * when data can be `null` or `undefined`.\n *\n * Notice that `Number.NaN` is not nullish and would not result in returning the\n * fallback!\n *\n * @param data - A nullish value.\n * @param fallback - A value of the same type as `data` that would be returned\n * when `data` is nullish.\n * @signature\n * R.defaultTo(data, fallback);\n * @example\n * R.defaultTo(\"hello\" as string | undefined, \"world\"); //=> \"hello\"\n * R.defaultTo(undefined as string | undefined, \"world\"); //=> \"world\"\n * @dataFirst\n * @category Other\n */\nexport function defaultTo<T, const Fallback extends FallbackOf<T>>(\n data: T,\n fallback: Fallback,\n): NonNullable<T> | Fallback;\n\n/**\n * A stricter wrapper around the [Nullish coalescing operator `??`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)\n * that ensures that the fallback matches the type of the data, and that the\n * data is nullish (`null` or `undefined`).\n *\n * Notice that `Number.NaN` is not nullish and would not result in returning the\n * fallback!\n *\n * @param fallback - A value of the same type as `data` that would be returned\n * when `data` is nullish.\n * @signature\n * R.defaultTo(fallback)(data);\n * @example\n * R.pipe(\"hello\" as string | undefined, R.defaultTo(\"world\")); //=> \"hello\"\n * R.pipe(undefined as string | undefined, R.defaultTo(\"world\")); //=> \"world\"\n * @dataLast\n * @category Other\n */\nexport function defaultTo<T, const Fallback extends FallbackOf<T>>(\n fallback: Fallback,\n): (data: T) => NonNullable<T> | Fallback;\n\nexport function defaultTo(...args: ReadonlyArray<unknown>): unknown {\n return purry(defaultToImplementation, args);\n}\n\nconst defaultToImplementation = <T, Fallback extends FallbackOf<T>>(\n data: T,\n fallback: Fallback,\n): NonNullable<T> | Fallback => data ?? fallback;\n"],"mappings":"wCA4DA,SAAgB,EAAU,GAAG,EAAuC,CAClE,OAAOA,EAAAA,EAAM,EAAyB,EAAK,CAG7C,MAAM,GACJ,EACA,IAC8B,GAAQ"}