Home > Web Front-end > JS Tutorial > body text

Calculate how long it takes to type a word in JavaScript

WBOY
Release: 2023-08-24 14:57:02
forward
1096 people have browsed it

计算在 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';
Copy after login

The output

const output = 7;
Copy after login

because the movement that occurs is-

'a' -> 'd' = 3
'd' -> 'a' = 3
'a' -> 'b' = 1
Copy after login

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));
Copy after login

Output

And the output in the console will be −

7
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!