Created
December 9, 2021 10:29
-
-
Save marcusschiesser/3ba46e4eb20fc6ea8bbe5e559e0bc11c to your computer and use it in GitHub Desktop.
Javascript type mapper - transforms properties of an object according to a type definition from string to float, int or boolean
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function mapTypes(map) { | |
return (obj) => { | |
const newObj = {}; | |
// eslint-disable-next-line no-restricted-syntax | |
for (const key in obj) { | |
if (Object.hasOwnProperty.call(obj, key)) { | |
let value = obj[key]; | |
const type = map[key]; | |
switch (type) { | |
case 'float': | |
value = parseFloat(value); | |
if (!Number.isNaN(value)) { | |
newObj[key] = value; | |
} | |
break; | |
case 'int': | |
value = parseInt(value, 10); | |
if (!Number.isNaN(value)) { | |
newObj[key] = value; | |
} | |
break; | |
case 'bool': | |
if (String(value).toLowerCase() === 'true') { | |
newObj[key] = true; | |
} else if (String(value).toLowerCase() === 'false') { | |
newObj[key] = false; | |
} | |
break; | |
default: | |
newObj[key] = value; | |
break; | |
} | |
} | |
} | |
return newObj; | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-env jest */ | |
import { mapTypes } from './mapper'; | |
describe('Mapper', () => { | |
const typeMapper = mapTypes({ price: 'float', hours: 'int', used: 'bool' }); | |
test('Maps float and int types', () => { | |
const result = typeMapper({ | |
price: '100.10', | |
hours: '88', | |
title: 'Hello', | |
}); | |
expect(result).toEqual({ price: 100.1, hours: 88, title: 'Hello' }); | |
}); | |
test('Maps boolean types', () => { | |
const result = [ | |
{ | |
used: 'true', | |
}, | |
{ | |
used: 'false', | |
}, | |
].map(typeMapper); | |
expect(result).toEqual([{ used: true }, { used: false }]); | |
}); | |
test('Invalid values are skipped', () => { | |
const result = typeMapper({ | |
price: 'Hello', | |
hours: 'Hello', | |
used: 'Hello', | |
title: 'Hello', | |
}); | |
expect(result).toEqual({ title: 'Hello' }); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment