|
| 1 | +# 0012 lengthConverter ( L-I ) |
| 2 | + |
| 3 | +## Problem |
| 4 | +Create a function that converts a given length value from one unit to another. |
| 5 | +The function should: |
| 6 | +- Accept a numeric length |
| 7 | +- Accept a fromUnit and toUnit |
| 8 | +- Support common metric and imperial units |
| 9 | +- Return the converted value rounded to 5 decimal places |
| 10 | +- Throw an error if an invalid unit is provided |
| 11 | + |
| 12 | +## Supported Units |
| 13 | +- meters |
| 14 | +- kilometers |
| 15 | +- centimeters |
| 16 | +- millimeters |
| 17 | +- inches |
| 18 | +- feet |
| 19 | +- yards |
| 20 | +- miles |
| 21 | + |
| 22 | +## Solution |
| 23 | +```js |
| 24 | +function lengthConverter(length, fromUnit, toUnit) { |
| 25 | + const units = { |
| 26 | + "meters": 1, |
| 27 | + "kilometers": 1000, |
| 28 | + "centimeters": 0.01, |
| 29 | + "millimeters": 0.001, |
| 30 | + "inches": 0.0254, |
| 31 | + "feet": 0.3048, |
| 32 | + "yards": 0.9144, |
| 33 | + "miles": 1609.34 |
| 34 | + }; |
| 35 | + |
| 36 | + if (!units[fromUnit] || !units[toUnit]) { |
| 37 | + throw new Error("Invalid unit"); |
| 38 | + } |
| 39 | + const meters = length * units[fromUnit]; |
| 40 | + console.log((meters / units[toUnit]).toFixed(3)); |
| 41 | + return (meters / units[toUnit]).toFixed(3); |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +## Test Cases |
| 46 | +```js |
| 47 | +removeDuplicates([2, 4, 8, 4, 2, 6, 9, 2, 6, 8, 10]); |
| 48 | +// Output: [2, 4, 8, 6, 9, 10] |
| 49 | + |
| 50 | +removeDuplicates([1, 1, 1, 4, 0, 6, -2, 2, 6, 7, 10]); |
| 51 | +// Output: [1, 4, 0, 6, -2, 2, 7, 10] |
| 52 | + |
| 53 | +removeDuplicates("zoom"); |
| 54 | +// Output: "zom" |
| 55 | + |
| 56 | +removeDuplicates("hello world"); |
| 57 | +// Output: "helo wrd" |
| 58 | +``` |
| 59 | + |
| 60 | +## How it works |
| 61 | +- Define a units object where each unit is mapped to its value in meters |
| 62 | +- Validate both fromUnit and toUnit |
| 63 | +- The input length is first converted into meters |
| 64 | +- Then we convert meters into the target unit |
| 65 | +- The result is rounded to 5 decimal places using toFixed(5) |
| 66 | +- Finally, the converted value is returned |
| 67 | + |
| 68 | +## References |
| 69 | +- [Wikipedia – Unit conversion](https://en.wikipedia.org/wiki/Unit_conversion) |
| 70 | +- [MDN – JavaScript Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) |
| 71 | + |
| 72 | + |
| 73 | +## Problem Added By |
| 74 | +- [GitHub](https://github.com/rimsha-shoukat) |
| 75 | + |
| 76 | +## Contributing |
| 77 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 78 | + |
| 79 | +Please make sure to update tests as appropriate. |
0 commit comments