diff --git a/Conversions/LengthConversion.js b/Conversions/LengthConversion.js new file mode 100644 index 0000000000..36aedd416c --- /dev/null +++ b/Conversions/LengthConversion.js @@ -0,0 +1,38 @@ +/** + * 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. + */ + +const lengthConversion = (length, fromUnit, toUnit) => { + // Define a dictionary to map units to meters + const meters = { + 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 (!(fromUnit in meters) || !(toUnit in meters)) { + throw new Error('Invalid units') + } + + // Perform the conversion + const metersFrom = length * meters[fromUnit] + const convertedLength = metersFrom / meters[toUnit] + + return convertedLength +} + +export { + lengthConversion +} diff --git a/Conversions/test/LengthConversion.test.js b/Conversions/test/LengthConversion.test.js new file mode 100644 index 0000000000..7618cb0b20 --- /dev/null +++ b/Conversions/test/LengthConversion.test.js @@ -0,0 +1,53 @@ +import { lengthConversion } from '../LengthConversion.js' + +describe('LengthConversion', () => { + it.each` + length | fromUnit | toUnit | expected + ${10} | ${'km'} | ${'m'} | ${10000} + ${100} | ${'m'} | ${'km'} | ${0.1} + ${5} | ${'cm'} | ${'mm'} | ${50} + ${12} | ${'ft'} | ${'inch'}| ${144.00000000000003} + `( + 'converts $length $fromUnit to $toUnit', + ({ length, fromUnit, toUnit, expected }) => { + try { + const result = lengthConversion(length, fromUnit, toUnit) + expect(result).toBe(expected) + } catch (error) { + expect(error).toBeUndefined() + } + } + ) + + it.each` + length | fromUnit | toUnit | expected + ${10} | ${'m'} | ${'km'} | ${0.01} + ${1000}| ${'mm'} | ${'cm'} | ${100} + ${1} | ${'inch'}| ${'ft'} | ${0.08333333333} + `( + 'converts $length $fromUnit to $toUnit (vice versa)', + ({ length, fromUnit, toUnit, expected }) => { + try { + const result = lengthConversion(length, fromUnit, toUnit) + expect(result).toBeCloseTo(expected, 10) // Close comparison due to floating-point precision + } catch (error) { + expect(error).toBeUndefined() + } + } + ) + + it.each` + length | fromUnit | toUnit | expectedError + ${10} | ${'km'} | ${'invalid'} | ${'Invalid units'} + ${5} | ${'invalid'} | ${'m'} | ${'Invalid units'} + `( + 'returns error message for invalid units: $fromUnit to $toUnit', + ({ length, fromUnit, toUnit, expectedError }) => { + try { + lengthConversion(length, fromUnit, toUnit) + } catch (error) { + expect(error.message).toBe(expectedError) + } + } + ) +})