Skip to content

Commit

Permalink
Add parseBool utility function (#39)
Browse files Browse the repository at this point in the history
Resolves #8
  • Loading branch information
drebrez authored Aug 22, 2024
1 parent 6ba22fe commit 5ace4fe
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions src/lib/boolean.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
12 changes: 12 additions & 0 deletions src/lib/boolean.ts
Original file line number Diff line number Diff line change
@@ -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";
}

0 comments on commit 5ace4fe

Please sign in to comment.