DEV Community

Cover image for My first whiteboard challenge
Mark Kop
Mark Kop

Posted on

My first whiteboard challenge

Yesterday I had the opportunity to take part in a job interview's process which presented a challenge to solve on a whiteboard.

It was my first coding-on-a-whiteboard experience and what seemed simple at first, actually had several details to pay attention.

The Challenge

Given the following input, the expected output should be:

// Input
[
  {
    id: "futebol",
    parent: "null"
  },
  {
    id: "bola",
    parent: "futebol"
  }
]

// Output
{
  futebol: {
    bola: {}
  }
}
Enter fullscreen mode Exit fullscreen mode

Being an array as input, immediately I thought about using the map high order function, but then realized the output should be a single object, so I've changed it to the reduce HoF.

By the time I was figuring out on how to create a new object when parent's value was null, I've got stuck in such abstraction given by reduce HoF that made me change the strategy to a simpler javascript loop with for.

After completing the code, the interviewer added another challenge by giving an extra input object { id: "chuteira", parent: "futebol"} and asked if the code would still work as intended.
That moment I've felt that wouldn't and some kind of object destructuring was needed to not override an object, however we've followed along.

The solution

What I've learned from this experience was some cool Javascript tricks and concepts, such as Dynamic Properties Keys (ES6) and accessing nested properties in objects. I've also practiced how to present ideas and logic on a whiteboard and communication.

Below it's the final code and the ES6 approach which I was initially going to use. Notice how longer, but more declarative is the first approach.

// Using Reduce, Spread Operator and Dinamic Property Keys
const reducedCategories = products.reduce((prevProduct, product) => {
  if (product["parent"] === "null") {
    return {
      ...prevProduct,
      [product["id"]]: {}
    };
  } else {
    return {
      ...prevProduct,
      [product["parent"]]: {
        ...prevProduct[product["parent"]],
        [product["id"]]: {}
      }
    };
  }
}, {});

// Using classic javascript
var classicCategories = {};
for (var i = 0; i < products.length; i++) {
  if (products[i]["parent"] === "null") {
    classicCategories[products[i]["id"]] = {};
  } else {
    var parent = products[i]["parent"];
    classicCategories[parent][products[i]["id"]] = {};
  }
}

Enter fullscreen mode Exit fullscreen mode

Which one do you prefer?

Top comments (0)