
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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';
Output
const output = 7;
because the movements that took place are −
'a' -> 'd' = 3 'd' -> 'a' = 3 'a' -> 'b' = 1
Example
The code for this will be −
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
- Related Questions & Answers
- Problem: Time taken by tomatoes to rot in JavaScript
- Time taken by savepoint to perform backup in SAP HANA
- How to measure time taken by a function in C?
- How to measure the time taken by a function in Java?
- Calculating excluded average - JavaScript
- Joining two strings with two words at a time - JavaScript
- Find time taken for signal to reach all positions in a string - C++
- Calculating factorial by recursion in JavaScript
- Calculating Josephus Permutations efficiently in JavaScript
- How to obtain the time taken for a method to be executed in TestNG?
- Find time taken for signal to reach all positions in a string in C++
- Convert given time into words in C++
- How to use TIME type in MySQL?
- Calculating average of an array in JavaScript
- Calculating median of an array in JavaScript