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