Skip to content

Commit

Permalink
Merge pull request #175 from hckrnews/feature/parse-Boolean
Browse files Browse the repository at this point in the history
Added Bool parsing
  • Loading branch information
w3nl authored Jun 1, 2022
2 parents 9732aeb + 43ecc2b commit a359d95
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 9 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@hckrnews/objects",
"description": "Create valid JavaScript objects",
"version": "4.0.5",
"version": "4.0.6",
"author": {
"name": "Pieter Wigboldus",
"url": "https://hckr.news/"
Expand Down
36 changes: 36 additions & 0 deletions src/__tests__/parser.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,40 @@ describe('Test parser.js', () => {
d: null,
});
});

it.each([
{ a: 'y', b: true },
{ a: 'yes', b: true },
{ a: 'Y', b: true },
{ a: 'YES', b: true },
{ a: 'true', b: true },
{ a: 'on', b: true },
{ a: 1, b: true },
{ a: true, b: true },
{ a: '1', b: true },
{ a: 'n', b: false },
{ a: 'bla', b: false },
{ a: 'false', b: false },
{ a: '0', b: false },
{ a: 0, b: false },
{ a: 2, b: false },
{ a: -1, b: false },
{ a: {}, b: false },
{ a: [], b: false },
])('It should parse the boolean values $a -> $b', ({ a, b }) => {
const input = {
a: null,
b: a,
c: null,
d: null,
};
const parse = new Parser({ schema: testSchema });

expect(parse.parseObject(input)).toEqual({
a: null,
b,
c: null,
d: null,
});
});
});
33 changes: 27 additions & 6 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,35 @@ export default class Parser {
return [key, subParser.parseObject(value)];
}

if (Type === Boolean && value.constructor === String) {
if (String(value) === '1') {
return [key, true];
}

return [key, String(value).toLowerCase() === 'true'];
if (Type?.constructor === Boolean || Type?.name === 'Boolean') {
return [key, this.parseBoolean(value)];
}

return Type ? [key, new Type(value).valueOf()] : [key, value];
}

/**
* Parse a boolean value.
*
* @param {*} value
*
* @return {boolean}
*/
parseBoolean(value) {
if (value.constructor === String) {
return ['true', 't', 'yes', 'y', 'on', '1'].includes(
value.trim().toLowerCase()
);
}

if (value.constructor === Number) {
return value.valueOf() === 1;
}

if (value.constructor === Boolean) {
return value.valueOf();
}

return false;
}
}

0 comments on commit a359d95

Please sign in to comment.