Codewars Closest elevator – Easy Solution Javascript (8 kyu)

This is the solution for the Codewars Closest elevator question in Javascript with a simple & easy to understand code and explanation.

Task:

Given 2 elevators (named “left” and “right”) in a building with 3 floors (numbered 0 to 2), write a function elevator accepting 3 arguments (in order):

  • left – The current floor of the left elevator
  • right – The current floor of the right elevator
  • call – The floor that called an elevator

It should return the name of the elevator closest to the called floor ("left"/"right").

In the case where both elevators are equally distant from the called floor, choose the elevator to the right.

Here’s the link to the kata – Closest elevator

Solution to Closest elevator Question:

The simple solution to the ‘Closest elevator’ question is to subtract left and right from call, and get the absolute value. Then, return the lowest value of the two. If both the values are the same, the else statement gets executed, as n<n is false.

//solution style 1 - easy to read and understand

function elevator(left, right, call) {
  return Math.abs(call - left) < Math.abs(call - right) ? 'left' : 'right';
}
//solution style 2 - single line

const elevator = (left, right, call) => 
Math.abs(call-left) < Math.abs(call-right) ? 'left' : 'right'

Leave a Comment