Skip to content

Commit 1f6b2bb

Browse files
committed
feat: parse boolean utility function
1 parent 546cf84 commit 1f6b2bb

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

packages/utilities/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ export * from './url_params_utils';
1010
export * from './code_hash_manager';
1111
export * from './hmac';
1212
export * from './storages';
13+
export * from './parse_boolean';
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Strictly parses a value to a boolean, returning `null` if the value is invalid.
3+
* - Returns `true` for: `true`, `1`, `'1'`, `'true'` (case-insensitive).
4+
* - Returns `false` for: `false`, `0`, `'0'`, `'false'` (case-insensitive).
5+
* - Returns `null` for any other value.
6+
*
7+
* @param value - The value to parse (unknown type).
8+
* @returns {boolean | null} The parsed boolean or null if the input is invalid.
9+
*/
10+
export const parseBooleanOrNull = (value: unknown): boolean | null => {
11+
if (value === true || value === 1) return true;
12+
if (value === false || value === 0) return false;
13+
14+
if (typeof value === 'string') {
15+
const lowerValue = value.trim().toLowerCase();
16+
if (lowerValue === 'true' || lowerValue === '1') return true;
17+
if (lowerValue === 'false' || lowerValue === '0') return false;
18+
}
19+
20+
// Return null for invalid/ambiguous input
21+
return null;
22+
};

test/utilities.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,3 +416,17 @@ describe('createInjectableRegExp()', () => {
416416
expect(utils.createInjectableRegExp(/[\w._~]+/)).toStrictEqual(/[\w._~]+/);
417417
});
418418
});
419+
420+
describe('parseBooleanOrNull', () => {
421+
it.each([true, 'true', 'TRUE', 'TrUe', 1, '1'])('Return true for %s value', (value) => {
422+
expect(utils.parseBooleanOrNull(value)).toBe(true);
423+
});
424+
425+
it.each([false, 'false', 'FALSE', 'FaLsE', 0, '0'])('Return false for %s value', (value) => {
426+
expect(utils.parseBooleanOrNull(value)).toBe(false);
427+
});
428+
429+
it.each([undefined, null, 'null', {}, [], -1])('Return null for %s value', (value) => {
430+
expect(utils.parseBooleanOrNull(value)).toBe(null);
431+
});
432+
});

0 commit comments

Comments
 (0)