DEV Community

Cover image for BFE.dev | 176. undefined to null
Nazmuz Shakib Pranto
Nazmuz Shakib Pranto

Posted on

BFE.dev | 176. undefined to null

Welcome to BFE.dev Challenges!

In this short article, I review my solution for BFE - #176 undefined to null challenge. Read on to see implementation details and my thought process for solving this coding challenge using JavaScript.

Mode: Easy

Problem

One of the differences between null and undefined is how they are treated differently in JSON.stringify().

JSON.stringify({a: null})      // '{"a":null}'
JSON.stringify({a: undefined}) // '{}'
JSON.stringify([null])         // '[null]'
JSON.stringify([undefined])    // '[null]'
Enter fullscreen mode Exit fullscreen mode

This difference might create trouble if there are missing alignments between client and server. It might be helpful to enforce using only one of them.

You are asked to implement undefinedToNull() to return a copy that has all undefined replaced with null

Example(s):

undefinedToNull({a: undefined, b: 'BFE.dev'})
// {a: null, b: 'BFE.dev'}
undefinedToNull({a: ['BFE.dev', undefined, 'bigfrontend.dev']})
// {a: ['BFE.dev', null, 'bigfrontend.dev']}
Enter fullscreen mode Exit fullscreen mode

Step-By-Step Process for Tackling a Coding Challenge:

  1. Read the problem multiple times until you clearly understand all the requirements

  2. Ask clarification questions to clarify potential confusion or knowledge gaps

  3. Identify all the inputs and outputs of the problem

  4. Ask to clarify any constraints of the problem, i.e., maximum input size, time complexity limits, or edge cases

  5. Write down at least 2 to 3 examples with input and output for testing later

  6. Break down the problem:

    • Outline each step at a basic level without diving into code yet.
    • Focus on a brute-force solution first, even if you know an optimized approach.
    • Write pseudocode for each step to visualize the logic.
    • Convert each pseudocode step into actual code.
    • Skip complex implementations initially and revisit them later.
    • Once all steps are implemented, seek confirmation before proceeding.
  7. Ask for permission to test out your implementation on a console

  8. Use the examples you wrote down earlier to test your code.

  9. If the actual result isn't the expected result, try to debug the problem by adding logs or using a debugger (if available)

  10. Discuss the time complexity and space complexity of the solution

  11. Think of ways to optimize your implementation to improve time and space complexity and to increase readability (if possible)

  12. Refactor your code for optimization and test again to ensure the results are still correct.

  13. Explain each step out loud to demonstrate your understanding and thought process.

Solution

/**
 * @param {any} arg
 * @returns any
 */
function undefinedToNull(arg) {
  if (typeof arg === 'undefined') return null;

  if (Array.isArray(arg)) return arg.map(each => undefinedToNull(each));

  if (typeof arg === 'object' && arg !== null) {
    return Object
      .entries(arg)
      .reduce((obj, [key, value]) => {
        obj[key] = undefinedToNull(value);
        return obj;
      }, {});
  }

  return arg;
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaway(s):

  • Use typeof to get the type of a variable in JavaScript. This is particularly useful in this example in identifying if an argument is undefined or an object.
  • Don't forget to account for nested values. When dealing with arrays or objects, recursion can automatically apply the same logic to deeply nested structures.
  • I used recursion to solve this problem, but you can also use for or while loops, so choose the approach that you find easier to understand.

As always, I welcome any feedback on the implementation details of this coding challenge. Otherwise, hope folks found this helpful!

Top comments (0)