]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-main/angular/number-formatter.pipe.ts
Use onpush strategy for dropdown
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / angular / number-formatter.pipe.ts
CommitLineData
68018040 1import { formatNumber } from '@angular/common'
2import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core'
9bf9d2a5 3
94676e63 4// Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts
9bf9d2a5 5
be447678 6@Pipe({ name: 'myNumberFormatter' })
9bf9d2a5 7export class NumberFormatterPipe implements PipeTransform {
9bf9d2a5 8
22078471
RK
9 /**
10 * @param x number
11 * @param n number of decimals to get (defaults to 1, needs to be >= 1)
12 */
13 static getDecimalForNumber (x: number, n = 1) {
14 const v = x.toString().split('.')
15 const f = v[1] || ''
16 if (f.length > n) return +f.substr(0, n)
17 return +f
18 }
19
68018040 20 private dictionary: Array<{max: number, type: string}> = [
21 { max: 1000, type: '' },
22 { max: 1000000, type: 'K' },
23 { max: 1000000000, type: 'M' }
24 ]
384ba8b7 25
68018040 26 constructor (@Inject(LOCALE_ID) private localeId: string) {}
27
9bf9d2a5
C
28 transform (value: number) {
29 const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1]
22078471
RK
30 const calc = value / (format.max / 1000)
31 const integralPart = Math.floor(calc)
32 const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc)
9bf9d2a5 33
22078471 34 return integralPart < 10 && decimalPart > 0
68018040 35 ? formatNumber(parseFloat(`${integralPart}.${decimalPart}`), this.localeId) + format.type
22078471 36 : `${integralPart}${format.type}`
9bf9d2a5
C
37 }
38}