Saturday, May 21, 2016

Solving a JS Coding Exercise: Week 1

Hi Everyone,

I'm going to start a weekly series where I walk through an online Javascript coding exercise. These posts are to give you a feel for the kinds of questions that will be asked of you in Javascript interviews. I will be drawing these questions from sources I find online, from my own experience being interviewed, and from the questions I ask people when I interview them.

Try to solve the problem yourself before reading my solutions. Otherwise, you won't grow.

This problem comes courtesy of Chris Chen.

Time Limit(optional): You should be able to do this in under 30 minutes. I'd aim for 15mins or so.

Here's a link to the live coding exercise:
http://codepen.io/chris-chen-nbcuni/pen/mnfBG

If that doesn't work, here's the problem description:
HTML:
<!--
  Instructions:
  When the value changes in the text field, multiply the 2 values and display in span with ID total.
  If the total is greater than 0, make the text green. Everything else make it red.
-->

<input id="value1" type="text" value="" /> x <span id="value2">1234</span> = <span id="total" class="other">?</span>

CSS:
.positive { color: green; }
.other { color: red; }

Javascript:








SOLUTION:
We need to perform a mathematical operation whenever someone changes the contents of the input box. Your first thought immediately should have been to assign an event listener to that input box. How?
// #1: get a reference to the input box and other elements
var oInput = document.getElementById('value1');
var CONST = 1234;

var oOutput = document.getElementById('total');
// #2: and assign it an event listener for the 'input' event
oInput.addEventListener('input',onInputEvent,false);

The input event fires whenever the contents of an <input> or <textarea> element change.
https://developer.mozilla.org/en-US/docs/Web/Events/input
You could probably solve this by listening to other events, but input makes the most sense here.
Now, we need to multiply the value in the <input> element by 1234 whenever the input changes, and check to see if it's greater than zero. We also want to display the product of this multiplication as well.

// #3:  write out the function for the event listener
function onInputEvent(){
  var nResult = CONST * parseInt(oInput.value);
  oOutput.innerHTML = nResult;
  if(nResult){
    oOutput.classList.remove('other');
    oOutput.classList.add('positive');
  }else{
    oOutput.classList.remove('positive');
    oOutput.classList.add('other');
  }
}

That does the trick. I prefer to get the references to the DOM elements outside of the listener function, so that they aren't rerun every time the event handler fires.

No comments:

Post a Comment