Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. import { Pipe, PipeTransform } from '@angular/core';
  2.  
  3. @Pipe({
  4. name: 'secondsToTime'
  5. })
  6. export class SecondsToTimePipe implements PipeTransform {
  7. static factors = {
  8. year: 31557600,
  9. month: 2629746,
  10. day: 86400,
  11. hour: 3600,
  12. minute: 60,
  13. sec: 1
  14. }
  15.  
  16. static showOnly = 3;
  17.  
  18.  
  19.  
  20. transform(seconds: number) {
  21. if (seconds == null) return "";
  22.  
  23. const { factors } = SecondsToTimePipe;
  24.  
  25. let result = '';
  26. let skippedFirstSpace = false;
  27. let shown = 0;
  28. for (const key in factors) {
  29. if (!factors.hasOwnProperty(key)) continue;
  30.  
  31. const factor = factors[key];
  32. const count = Math.floor(seconds / factor);
  33. if (count === 0) continue;
  34.  
  35. // show only x parameters
  36. // (i.e. don't show miliseconds if we also display years, keep it concise).
  37. if (shown++ > SecondsToTimePipe.showOnly) break;
  38.  
  39. // only start adding spaces after the first match.
  40. const space = skippedFirstSpace ? ' ' : '';
  41. skippedFirstSpace = true;
  42.  
  43. // add an s to put words in plural.
  44. const plural = (count > 1) ? 's' : '';
  45.  
  46. // put everything together.
  47. result += `${space}${count} ${key}${plural}`;
  48. seconds -= factor * count;
  49. }
  50. return result;
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement