Hey guys,
I’ve been playing with dynamic type checking for functions.
I figured out how to add a method to Function.prototype that type checks an argument value and short circuits the main function call if undefined or not the correct type.
It then returns an empty value of that type (so it wont return undefined index in looping array)
If it is correct it calls return this(x)
e.g.
makeUpperCase.type('string' , 12)
// short circuits function returns ’ ’
makeUpperCase.type('string', 'hello')
// calls makeUpperCase('hello')
returns ‘HELLO’
The full code is below, can anyone think of any edge cases where this might fall over?
Thanks for your help
const arr = ['jim',false,'bill','dave', 123];
let str = 'hotel california'
var toUpper = x => x.toUpperCase();
Function.prototype.type = function(type,x){
if(!x || typeof x !== type){
switch(type){
case 'string': return ''; break;
case 'number': return 0 ; break;
case 'boolean': return false; break;
default: return false;
}
}
return this(x)
}
toUpper.type('string', str);
//'HOTEL CALIFORNIA'
toUpper.type('number', str);
// returns 0
toUpper.type('boolean',str)
// returns false
//mutates arr returns last value
for(i = 0; i < arr.length; i++){
arr[i] = toUpper.type('string', arr[i])}
// [ 'JIM', '', 'BILL', 'DAVE', '' ]
//mutates arr returns last value
for(let i of arr){toUpper.type('string', i)}
//[ 'JIM', '', 'BILL', 'DAVE', '' ]
// maps arr returns new arr
arr.map(x => toUpper.type('string',x))
//[ 'JIM', '', 'BILL', 'DAVE', '' ]
console.log(arr)
BTW forEach doesn’t work on this…