The task is to implement a function that replaces undefined with null.
The boilerplate code
function undefinedToNull(arg) {
// your code here
}
If it is a single value
if(arg === undefined) return null;
If the value is an array, create a new array with the same length
if(Array.isArray(arg)) {
const result = new Array(arg.length);
}
Go through each element one by one, then run it recursively for each element
for(let i = 0; i < arg.length; i++) {
result[i] = undefinedToNull(arg[i]);
}
If the value is an object, create a new empty object
if(arg !== null && typeof arg === 'object') {
const result = {};
}
Go through every key in the object, apply the function to each value and assign the result back to the same key
for(const key in arg) {
result[key] = undefinedToNull(arg[key]);
}
The final code
function undefinedToNull(arg) {
// your code here
if(arg === undefined) return null;
if(Array.isArray(arg)) {
const result = new Array(arg.length);
for(let i = 0; i < arg.length; i++) {
result[i] = undefinedToNull(arg[i]);
}
return result;
}
if(arg !== null && typeof arg === 'object') {
const result = {};
for(const key in arg) {
result[key] = undefinedToNull(arg[key]);
}
return result;
}
return arg;
}
That's all folks!
Top comments (0)