Calculating time taken to type words in JavaScript

Suppose we have a keyword, which instead of the traditional qwerty type key mapping, maps keys simply according to the english alphabetic order i.e., abcde...

Before we dive into the problem, we have to make the following two assumptions −

  • Currently our fingertip is placed at index 0, i.e., the key 'a

  • The time taken to move from one key to some other is the absolute difference of their index, for example the time taken to move from 'a' to 'k' will be |0 - 10| = 10

We are required to write a JavaScript function that takes in a string of english lowercase alphabets and calculates and returns the time we will be required to type the string.

For example −

If the input string is −

const str = 'dab';


const output = 7;

because the movements that took place are −

'a' -> 'd' = 3
'd' -> 'a' = 3
'a' -> 'b' = 1


The code for this will be −

 Live Demo

const str = 'dab';
const findTimeTaken = (str = '') => {
   let timeSpent = 0;
   const keyboard = 'abcdefghijklmnopqrstuvwxyz';
   let curr = 'a';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      const fromIndex = keyboard.indexOf(curr);
      const toIndex = keyboard.indexOf(el);
      const time = Math.abs(fromIndex - toIndex);
      curr = el;
      timeSpent += time;
   return timeSpent;


And the output in the console will be −