Created
December 18, 2019 18:15
-
-
Save ecasilla/48b2f11d0292ab700a953c30c71ee5cb to your computer and use it in GitHub Desktop.
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
const input = { | |
x: 'hello world', | |
y: 2, | |
f: true, | |
z: { | |
a: [1,2,3], | |
b: new Set([1,2,3]), | |
c: new Map([['hello', 'world']]), | |
d: null, | |
e: undefined | |
}, | |
g: () => {} | |
} | |
const STRING_TYPE = 'string'; | |
const NUMBER_TYPE = 'number'; | |
const BOOLEAN_TYPE = 'boolean'; | |
const FALSY_TYPE = 'falsy'; | |
const OBJECT_TYPE = 'object'; | |
const FUNCTION_TYPE = 'function'; | |
const type = { | |
[STRING_TYPE]: 'sinon.match.string', | |
[NUMBER_TYPE]: 'sinon.match.number', | |
[FALSY_TYPE]: 'sinon.match.falsy', | |
[BOOLEAN_TYPE]: 'sinon.match.bool', | |
'array': 'sinon.match.array', | |
'function': 'sinon.match.func', | |
'map': 'sinon.match.map', | |
'set': 'sinon.match.set' | |
} | |
function gen(arg) { | |
const keys = Object.keys(arg); | |
if (!keys && !keys.length) { | |
return {}; | |
} | |
return keys.reduce((acc, val) => { | |
if (typeof arg[val] === STRING_TYPE) { | |
acc[val] = type[STRING_TYPE] | |
return acc; | |
} | |
if (typeof arg[val] === NUMBER_TYPE) { | |
acc[val] = type[NUMBER_TYPE] | |
return acc; | |
} | |
if (typeof arg[val] === BOOLEAN_TYPE) { | |
acc[val] = type[BOOLEAN_TYPE] | |
return acc; | |
} | |
if (arg[val] instanceof Map) { | |
acc[val] = type['map'] | |
return acc; | |
} | |
if (arg[val] instanceof Set) { | |
acc[val] = type['set'] | |
return acc; | |
} | |
if (arg[val] === null || arg[val] === undefined) { | |
acc[val] = type[FALSY_TYPE] | |
return acc; | |
} | |
if (typeof arg[val] === OBJECT_TYPE && Array.isArray(arg[val])) { | |
acc[val] = type['array'] | |
return acc; | |
} | |
if (typeof arg[val] === OBJECT_TYPE && arg[val] !== null) { | |
acc[val] = gen(arg[val]) | |
return acc; | |
} | |
if (typeof arg[val] === FUNCTION_TYPE) { | |
acc[val] = type[FUNCTION_TYPE] | |
return acc; | |
} | |
return acc; | |
}, {}); | |
} | |
const x = gen(input); | |
console.log(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output object values will be strings so a quick find and replace of all single quotes and then deleting of those single quotes will get a working object to sinon.assert against,
// Sample Output