forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLengthConversion.js
More file actions
Latest commit
36 lines (31 loc) · 999 Bytes
/
Copy pathLengthConversion.js
File metadata and controls
36 lines (31 loc) · 999 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Converts a length from one unit to another.
*
* @param {number} length - The length to convert.
* @param {string} fromUnit - The unit to convert from (e.g., "km", "m", "cm").
* @param {string} toUnit - The unit to convert to (e.g., "km", "m", "cm").
* @returns {number} The converted length.
* @throws {Error} If the units are invalid or not found in the conversion dictionary.
*/
constlengthConversion=(length,fromUnit,toUnit)=>{
// Define a dictionary to map units to meters
constmeters={
mm: 0.001,
cm: 0.01,
m: 1,
km: 1000,
inch: 0.0254,
ft: 0.3048,
yd: 0.9144,
mi: 1609.34
}
// Check if the units are in the dictionary, otherwise, throw an error
if(!(fromUnitinmeters)||!(toUnitinmeters)){
thrownewError('Invalid units')
}
// Perform the conversion
constmetersFrom=length*meters[fromUnit]
constconvertedLength=metersFrom/meters[toUnit]
returnconvertedLength
}
export{lengthConversion}