Finding the sum of floors covered by an elevator in JavaScript


Problem

We are required to write a JavaScript function that takes in an array that represents the floor numbers at which a building lift stopped during an interval of time.

From that data, our function should return the count of total number of floors covered by the lift in that time.

Example

Following is the code −

 Live Demo

const arr = [7, 1, 7, 1];
const floorsCovered = (arr = []) => {
   let res = 0;
   for (let i = 0; i < arr.length; i++){
      if (arr[i] > arr[i+1]){
         res += arr[i] - arr[i+1];
      };
      if (arr[i] < arr[i+1]){
         res += arr[i+1] - arr[i];
      }
   };
   return res;
};
console.log(floorsCovered(arr));

Output

Following is the console output −

18

Updated on: 19-Apr-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements