Created
May 7, 2020 01:58
-
-
Save felixchez/aa00f9a208c912a0beb105125482abda to your computer and use it in GitHub Desktop.
TypeScript: Unit Conversion Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert from units to another units e.g. from square feet to acres | |
* return original value if conversion units are not supported | |
* Usage: | |
* const convertedValue = convert(100).from('acres').to('square feet'); | |
* expected: | |
* 4356000 | |
*/ | |
class Converter { | |
private toUnits: string; | |
private fromUnits: string; | |
private convertedValue: number; | |
constructor(private value: string) { | |
this.convertedValue = Number(value); | |
} | |
public to(units: string, fractionDigits: number = 0): string { | |
this.toUnits = units.toLowerCase(); | |
if (this.toUnits === 'square feet' && this.fromUnits === 'acres') { | |
this.convertedValue = this.convertedValue * 43560; | |
} else if (this.toUnits === 'acres' && this.fromUnits === 'square feet') { | |
this.convertedValue = this.convertedValue / 43560; | |
} else { | |
// return original value | |
return this.value; | |
} | |
return this.convertedValue.toFixed(fractionDigits); | |
} | |
public from(units: string): Converter { | |
this.fromUnits = units.toLowerCase(); | |
return this; | |
} | |
} | |
export const convert = (value: string) => { | |
return new Converter(value); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment