DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 81

The task is to implement a function that replaces undefined with null.

The boilerplate code

function undefinedToNull(arg) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If it is a single value

if(arg === undefined) return null;
Enter fullscreen mode Exit fullscreen mode

If the value is an array, create a new array with the same length

 if(Array.isArray(arg)) {
    const result = new Array(arg.length);
  }
Enter fullscreen mode Exit fullscreen mode

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]);
    }
Enter fullscreen mode Exit fullscreen mode

If the value is an object, create a new empty object

if(arg !== null && typeof arg === 'object') {
    const result = {};
  }
Enter fullscreen mode Exit fullscreen mode

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]);
    }
Enter fullscreen mode Exit fullscreen mode

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;
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)