Added math functions
All checks were successful
Build / Build NPM Project (push) Successful in 1m29s
Build / Tag Version (push) Successful in 19s
Build / Publish (push) Successful in 26s

This commit is contained in:
Zakary Timson 2024-05-27 13:51:41 -04:00
parent 86196c3feb
commit 9350c837e5
3 changed files with 47 additions and 1 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.9.0",
"version": "0.10.0",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@ -4,6 +4,7 @@ export * from './download';
export * from './emitter';
export * from './errors';
export * from './logger';
export * from './math';
export * from './misc';
export * from './objects';
export * from './promise-progress';

45
src/math.ts Normal file
View File

@ -0,0 +1,45 @@
/**
* Convert decimal number to fraction
*
* @example
* ```js
* dec2Frac(1.25) // Outputs: "1 1/4"
* ```
*
* @param {number} num Number to convert
* @return {string} Fraction with remainder
*/
export function dec2Frac(num: number) {
const gcd = (a: number, b: number): number => {
if (b < 0.0000001) return a;
return gcd(b, ~~(a % b));
};
const len = num.toString().length - 2;
let denominator = Math.pow(10, len);
let numerator = num * denominator;
const divisor = gcd(numerator, denominator);
numerator = ~~(numerator / divisor);
denominator = ~~(denominator / divisor)
const remainder = ~~(numerator / denominator);
numerator -= remainder * denominator;
return `${remainder ? remainder + ' ' : ''}${~~(numerator)}/${~~(denominator)}`;
}
/**
* Convert fraction to decimal number
*
* @example
* ```js
* fracToDec('1 1/4') // Outputs: 1.25
* ```
*
* @param {string} frac Fraction to convert
* @return {number} Faction as a decimal
*/
export function fracToDec(frac: string) {
let split = frac.split(' ');
const whole = split.length == 2 ? Number(split[0]) : 0;
split = (<string>split.pop()).split('/');
return whole + (Number(split[0]) / Number(split[1]));
}