diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fba1e5..2113283 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- added `parseBool` utility function + ## [0.6.0] - 2024-06-26 ### dependabot: \#37 Bump braces from 3.0.2 to 3.0.3 diff --git a/src/lib/boolean.spec.ts b/src/lib/boolean.spec.ts new file mode 100644 index 0000000..5931197 --- /dev/null +++ b/src/lib/boolean.spec.ts @@ -0,0 +1,42 @@ +import { parseBool } from "./boolean"; + +describe("boolean tests", () => { + test.each([ + // Test cases like in C# + // https://github.com/dotnet/runtime/blob/main/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/BooleanTests.cs + [null as unknown as string, false], + [undefined as unknown as string, false], + [0 as unknown as string, false], + [1 as unknown as string, false], + [10 as unknown as string, false], + [new Date() as unknown as string, false], + ["True", true], + ["true", true], + ["TRUE", true], + ["tRuE", true], + [" True ", true], + ["True\0", true], + [" \0 \0 True \0 ", true], + ["False", false], + ["false", false], + ["FALSE", false], + ["fAlSe", false], + ["False ", false], + ["False\0", false], + [" False \0\0\0 ", false], + ["", false], + [" ", false], + ["Garbage", false], + ["True\0Garbage", false], + ["True\0True", false], + ["True True", false], + ["True False", false], + ["False True", false], + ["Fa lse", false], + ["T", false], + ["0", false], + ["1", false], + ])('parseBool("%s")', (value, expected) => { + expect(parseBool(value)).toBe(expected); + }); +}); diff --git a/src/lib/boolean.ts b/src/lib/boolean.ts new file mode 100644 index 0000000..3d95196 --- /dev/null +++ b/src/lib/boolean.ts @@ -0,0 +1,12 @@ +import { isNullOrEmpty } from "./string"; + +/** + * Converts a string to a boolean + * @param value The string to convert + * @returns The parsed boolean + */ +export function parseBool(value?: string): boolean { + // Similar to C# implementation that trims also null characters + // https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Boolean.cs#L277 + return !isNullOrEmpty(value) && value?.replace(/[\s\0]/g, "").toLowerCase() === "true"; +}