Home  >  Article  >  Web Front-end  >  Calculate how long it takes to type a word in JavaScript

Calculate how long it takes to type a word in JavaScript

WBOY
WBOYforward
2023-08-24 14:57:021109browse

计算在 JavaScript 中输入单词所需的时间

Suppose we have a keyword that is not a traditional qwerty type key mapping, but simply maps keys according to English alphabetical order, that is, abcde...

Before we delve into the problem, we have made the following two assumptions -

  • Currently our fingertip is at index 0, which is the key 'a

  • The time required to move from one key to another is the absolute difference of their indexes, for example the time required to move from "a" to "k" will be |0 - 10| = 10

We need to write a JavaScript function that accepts a string of English lowercase letters and calculates and returns the time required to enter the string.

For example-

If the input string is-

const str = 'dab';

The output

const output = 7;

because the movement that occurs is-

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

Example

The code is -

Real-time demonstration

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;
};
console.log(findTimeTaken(str));

Output

And the output in the console will be −

7

The above is the detailed content of Calculate how long it takes to type a word in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete