feat: Add Length Conversion (#1390)

This commit is contained in:
Aakash Giri
2023-10-02 12:35:39 +05:30
committed by GitHub
parent 0604d06ac6
commit 6291d4b611
2 changed files with 91 additions and 0 deletions

View File

@ -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
}

View File

@ -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)
}
}
)
})