diff --git a/src/angular/frontend/src/app/pipes/short-number.pipe.spec.ts b/src/angular/frontend/src/app/pipes/short-number.pipe.spec.ts new file mode 100644 index 0000000..d9c5f5d --- /dev/null +++ b/src/angular/frontend/src/app/pipes/short-number.pipe.spec.ts @@ -0,0 +1,8 @@ +import { ShortNumberPipe } from './short-number.pipe'; + +describe('ShortNumberPipe', () => { + it('create an instance', () => { + const pipe = new ShortNumberPipe(); + expect(pipe).toBeTruthy(); + }); +}); diff --git a/src/angular/frontend/src/app/pipes/short-number.pipe.ts b/src/angular/frontend/src/app/pipes/short-number.pipe.ts new file mode 100644 index 0000000..6c1bb1b --- /dev/null +++ b/src/angular/frontend/src/app/pipes/short-number.pipe.ts @@ -0,0 +1,33 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({ + name: 'shortNumber', + pure: true +}) +export class ShortNumberPipe implements PipeTransform { + + private readonly suffixes = ['k', 'M', 'G', 'T', 'P', 'E']; + + transform(input: number, maxDecimals: number = 0): string { + + if (Number.isNaN(input)) { + return 'NaN'; + } + + if (input < 1000) { + return input.toString(); + } + + const exp = Math.floor(Math.log(input) / Math.log(1000)); + const fixed = (input / Math.pow(1000, exp)).toFixed(maxDecimals + 1); + const split = fixed.split('.'); + const integer = split[0]; + const decimal = split.length > 1 ? (+(+('0.' + split[1])).toFixed(maxDecimals + 1)).toString().slice(2) : null; + const d = decimal && decimal.length > maxDecimals ? decimal.slice(0, maxDecimals) : decimal; + const sliced = integer + (d ? '.' + d : ''); + const suffix = this.suffixes[exp - 1]; + + return `${sliced} ${suffix}`; + } + +}