All files / src/app/graphs/sparkline sparkline.component.ts

100% Statements 27/27
83.33% Branches 5/6
100% Functions 9/9
100% Lines 23/23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 391x             1x   1x 1x 13x 13x 13x 13x     1x 7x 1x       5x 5x 5x 5x 15x 15x 15x     1x 6x 6x 18x   1x  
import { Component, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
 
@Component({
  selector: 'sparkline',
  templateUrl: './sparkline.component.html',
})
export class SparklineComponent implements OnInit {
 
  @Input() id: string;
  @Input() history: number[];
  points = '';
  width = 100;
  height = 30;
  margin = 3;
  constructor() { }
 
  ngOnInit() {
    if (this.history && this.history.length) {
      this.draw();
    }
  }
 
  draw() {
    const x_spacing = this.history.length > 1 ? this.width / (this.history.length - 1) : 0;
    this.points = '';
    this.points = this.normalizeData(this.history)
      .map(d => (d * (this.height - (2 * this.margin))) + this.margin)  // scale y values
      .map((d, i) => { return {x: i * x_spacing, y: d}; })        // apply x spacing
      .map(d => `${d.x},${d.y}`).join(' ');                       // convert to string containing coords
  }
 
  normalizeData(data: number[]): number[] {
    const max = Math.max( ...data);
    const min = Math.min( ...data);
    return data.map(d => ((d - min) / (max - min)) );
  }
}