Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding letter distance in strings - JavaScript
We are required to write a JavaScript function that takes in a string as first argument and two single element strings. The function should return the distance between those single letter strings in the string taken as first argument.
For example −
If the three strings are −
const str = 'Disaster management'; const a = 'i', b = 't';
Then the output should be 4 because the distance between 'i' and 't' is 4
Understanding Letter Distance
Letter distance is the absolute difference between the index positions of two characters in a string. For example, in "Disaster", 'i' is at index 1 and 't' is at index 5, so the distance is |1 - 5| = 4.
Example
Following is the code −
const str = 'Disaster management';
const a = 'i', b = 't';
const distanceBetween = (str, a, b) => {
const aIndex = str.indexOf(a);
const bIndex = str.indexOf(b);
if(aIndex === -1 || bIndex === -1){
return false;
}
return Math.abs(aIndex - bIndex);
};
console.log(distanceBetween(str, a, b));
Output
Following is the output in the console −
4
How It Works
The function uses indexOf() to find the first occurrence of each character. If either character is not found, it returns false. Otherwise, it calculates the absolute difference using Math.abs().
Enhanced Example with Multiple Cases
const distanceBetween = (str, a, b) => {
const aIndex = str.indexOf(a);
const bIndex = str.indexOf(b);
if(aIndex === -1 || bIndex === -1){
return -1; // Return -1 for not found
}
return Math.abs(aIndex - bIndex);
};
// Test cases
console.log(distanceBetween('Hello World', 'e', 'o')); // Distance between 'e' and first 'o'
console.log(distanceBetween('JavaScript', 'J', 't')); // Distance between 'J' and 't'
console.log(distanceBetween('Programming', 'x', 'y')); // Characters not found
1 9 -1
Conclusion
This function efficiently calculates letter distance using indexOf() and Math.abs(). It handles cases where characters don't exist by returning a false or error value.
