4 more relevant JavaScript questions to help fix the broken coding interview
Tags: javascript, career, discuss
Published: 2019-05-08 13:37:34

 
As a quick refresher, there is a general sense that technical interviewing is broken. JavaScript is probably the most popular programming language today and certainly part of the top fives. 

Hiring the right candidate in the JS world - which has become a multiverse - is turning into an experimental art form. 

I have, like many before and many more to come, been a witness of the impact of a poor screening process and this is my attempt to be a part of the solution. 

You can read more about my mission statement in the [first article](https://dev.to/adyngom/28-relevant-javascript-interview-questions-part-i-the-first-4-2a16) of the series but without further ado here is your next relevant four in descending order for a change.

**#8. Input autocomplete**
**_Best suited for:_** Senior | Expert **Stage:** At home | Round 2 | Onsite

**#8A. The challenge**
The UX team has insisted that the country search input form needed to be more user-friendly.
 
They have their mind made on a "simple" autocomplete search box. What's not so simple and not obvious to the UX team, is that you have a huge dataset of possible results that would not be feasible to store on the client side. 

Your task is to create a program that listens to user input events and fetches a list of possible matches. The UX team is not a big fan of dirty matching and wants the list to only show the country names that start with the search term entered by the user - oh and they want matches to be highlighted by the way on the list results

**8B. The context**
I have had similar tests provided and with usually a 48 to 72 hours to submit it back. I strongly advise that you use all the time allocated to come up with the most refined solution available.
 
This has the advantage to mimic to a certain extent what an actual user story might be and you are given time to execute. 

And please, please don't just go blindly copy and paste a solution that you do not have a full grasp on. 

You will be expected to come on site or online to talk about your solution, your reasoning and more than often a 'feature creep' will happen during evaluation to see how you will handle it. 

For this particular problem, the async nature of the search and filter is going to be the first hurdle, but I would not personally start there. I would probably start with a small set of local data and focus on making the autocomplete and highlight as solid as possible.

As an interviewer I would love to see the candidate talk about and integrate all or most of the concepts below:

- Throttle [link](https://css-tricks.com/debouncing-throttling-explained-examples/)
- Debounce [link](https://davidwalsh.name/javascript-debounce-function)
- Caching
- Memoization [link](https://medium.freecodecamp.org/understanding-memoize-in-javascript-51d07d19430e)
- Error Handling 

Take-homes are more challenging than they might seem at first. Usually, enough is given to get you started, but a lot is expected on your delivery.

**#7 Mini testing library**
**_Best suited for:_** Junior | Senior | Expert **Stage:** Round 3 | Onsite

**#7A. The challenge**
The dev team is shyly making its debut to the TDD approach. They don't want to commit yet to a full-fledged library but want to write simple tests directly on the console to test their most important functions. They have dubbed the experiment project dotLog and have provided the initial structure below:

<code>
```javascript
var dotLog = ( function() {
 return {
    describe(desc = 'test description:', testSet = []) {
        console.groupCollapsed(`${desc}: 0 passed - 0 failed`);
            // console out each test
        console.groupEnd();
    }
 }
}());
```
</code>

The **describe** method takes in a test label string and an array of test objects. The test object uses the following model:
<code>
```javascript
var testOne = { rule: ( 3 < 4), label: " 3 is less than 4" };
var testTwo = { rule: (Math.max.apply(null,[3,4,1,2,0]) === 4), label: " should output 4" };
```
</code>

Now those can be added to a testSet and be passed to the **describe** method
<code>
```javascript
var testSet = [testOne, testTwo];
dotLog.describe("Basic Math tests:", testSet);
Given the following 'naïve' function
function sum (x, y) {
	return x + y;
}
```
</code>

Fix it and the describe method so the following output is displayed:
<code>
```javascript
sum(): 3 passed - 1 failed
    √ Should return 0 if no arguments
    √ Should add two numbers
    √ Should add up any amount of numbers
    x Should convert any non-digit to 0 and return the right amount
```
</code>

**#7B. The context**
I have had my share of rejections but have also been very successful at landing the job. In all the interviews I have been through, only two companies have ever presented a challenge similar to this one.
 
The particularity of it was that I was actually seating with the entire development team, where would eventually be my work station and participated in the standup and was given half the day to solve for the problem. At the end of the four hours, I was taken to lunch and bid farewell.

Though I landed both of those, the interesting part was the process. I got to work directly in what would be my daily environment, the challenge was an actual user story in their backlog. 

I could not cheat on my soft skills if I wanted to be successful, I had to reach out to my "soon to be" teammates to find out more details, or a quick setup issue. I had to submit my changes via a PR. 

Word of advice, commit often and use descriptive messages about your changes.

In summary, I think companies can invest some time in accommodating this type of setup. Another approach might be to give it as an at home exercise with a time limit and have the candidate come and discuss her solution onsite with the team.

**#6 Vending machine**
**_Best suited for:_** Junior | Senior | Expert **Stage:** Round 2 | Round 3 | Onsite

**#6A. The challenge**
Bob runs a successful Vending Machine business. He wants to add an interface that makes them a bit user-friendly and make it easy to add and track inventory. Below is the typical inventory model for the machines:
<code>
```javascript
const drinks = {
    1: { name: "Mango Juice", stock: 2 },
    2: { name: "Banana Smoothies", stock: 2 },
    3: { name: "Guava Mix", stock: 1 },
    4: { name: "Citrus Blend", stock: 3 }
  };
```
</code>

Write a program that creates an instance of the Vending Machine (VM) with the following specifications:

The VM needs to be passed an inventory object in order to create an instance
If the object is not passed, the program should throw a descriptive error:
<code>
```javascript
const vm = new VM(drinks); // instance get created
// but
const emptyVM = new VM(); // throws a no inventory error
```
</code>

VM should assign the newly passed inventory to a private drinks variable that is not modifiable from the instance
<code>
```javascript
vm.drinks; // should output undefined
```
</code>

VM should have a callable sale method that takes the drink id as an input and return a success message if in stock or a failed message if out of stock
VM will always deduct one (1) from the product id stock after a successful sale
<code>
```javascript
vm.sale(1);
// output: 1 Mango Juice - Thank you, come again!!
vm.sale(1);
// output: 1 Mango Juice - Thank you, come again!!"
vm.sale(1);
// output: Mango Juice is out of stock :( Come back tomorrow
vm.sale(4);
// output: 1 Citrus Blend - Thank you, come again!!
```
</code>

Finally VM should also have a callable stock method. It does not take any parameters and should display the total count of available drinks. 

The drinks object given as an example has a total of 8 drinks. After buying 2 mango juice, the output of the stock method should 6. it should also output 'Out of stock' if empty.
<code>
```javascript
vm.stock(); // should output total of all drinks left or Out of stock
```
</code>

**#6B. The context**
Function with a constructor, new ES6 class, or Object create?? There are so many ways to approach this that I hope that the interviewer should be as prepared as the candidate.

A solid understanding of closures is going to help tremendously. It will be interesting also to see how the candidate approach scope and private variable and see if any design patterns are implicitly or explicitly used.

I think that no matter the level of the candidate, this type of exercise should allow touching on many key concepts of the JS language.

**#5 Code analysis and possible refactor**
**_Best suited for:_** Senior | Expert **Stage:** Round 2 | Round 3 | Onsite

**#5A. The challenge**
The sales team wants to have a small program that helps them remove any duplicates from a batch of tickets. Tickets batches are usually between **1,000** to **10,000** unfiltered items. The following solutions have been submitted by 3 developers in your team.

**Developer 1**
<code>
```javascript
if( !Array.prototype.uniq ) {
    Array.prototype.uniq = function() {
        let _singles = [];
        const arr = this;
        for ( let i = 0; i < arr.length; i++ ) {
            if(_singles.indexOf(arr[i]) === -1 ) {
                _singles.push( arr[i] );
            }
        }
        return _singles;
    }
}
```
</code>

**Developer 2**
<code>
```javascript
if(!Array.prototype.uniq) {
    Array.prototype.uniq = function() {
        return this.reduce( (arr, val) => {
            if (!arr.includes(val)) arr.push(val);
            return arr;
        }, [] );
    }
}
```
</code>

**Developer 3**
<code>
```javascript
if(!Array.prototype.uniq) {
   Array.prototype.uniq = function() {
       return new Set([...this]);
   }
}
```
</code>

Two tests files are provided [**onekTickets.js**](https://gist.github.com/adyngom/748873da9cb37828765216a36e7b7ec2) and [**tenkTickets.js.**](https://gist.github.com/adyngom/62c25502eed121e9092c97fd9041afa0)

Only one solution can be pushed to production. Which, if any, would you pick based on readability and performance?

Can any of the proposed solutions be even more optimized to get to a better one?
What would be the PR message you will leave for each of the developers regarding their solution and why it was or was not chosen?

**#5B. The context**
In a normal development environment, you will be expected to read, evaluate and eventually critique other people's code.

The PR reviews are a critical step in making sure quality code is being pushed to the main repo.

Now each team or company can have their own take about how to define quality, but cannot walk away from clearly outlining standards, conventions and coding culture.

This type of question is both beneficial to the employer but to the candidate as well. Your main interaction with the team will be through similar exercises on a daily basis.

As an interviewer, my expectation will be for the candidate to reference some benchmarking tools to help determine which block of code is the fastest.

I surely will be impressed if she could eyeball it and clearly explain why, but since we are talking about giving feedback, it will be always easier to show rather than just tell.

**console.time** and **console.timeEnd** might kick off the conversation in the right direction, [jsperf.com](jsperf.com) is also one the industry's favorite, but ultimately looking for, suggesting, doing a basic setup and running a quick benchmark would be a clear winner.

Finally, I would like to have an open discussion about readability, and maybe why sometimes it might be beneficial to sacrifice a little speed in spite of it.

**In closing**
This ends the second batch. Today we have introduced a DOM-related exercise with the input autocomplete. Expect a lot more of those to come in the next installment. 

In the meantime don't forget to share, clap or whatnots but most important to add to the discussion in the comments. 

Cheers