all files / utils/ index.js

100% Statements 24/24
100% Branches 10/10
100% Functions 4/4
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                                       
 
'use strict'
 
// dependencies
const figures = require('figures')
const path = require('path')
const hrtime = require('pretty-hrtime')
const bytes = require('pretty-bytes')
 
// cache this value as a constant, we assume it never changes
const pwd = process.cwd()
 
/**
 * Helper for outputting an absolute path relative to pwd.
 *
 * @param {String} to  The absolute path to render.
 * @return {String} relative
 */
exports.relative = function (to) {
  if (pwd === to) return '.'
  return path.relative(pwd, to)
}
 
/**
 * Helper for determining the real size in bytes of an input buffer/string.
 *
 * @param {Buffer} input  The input to measure.
 * @param {Boolean} raw   Turn on to get a raw number.
 * @return {String} size
 */
exports.size = function (input, raw) {
  let size = input ? Buffer.byteLength(input) : 0
  return raw ? size : bytes(size)
}
 
exports.sizeDiff = function (a, b) {
  let before = bytes(a)
  let after = bytes(b)
  let arrow = figures.arrowRight
  let delta = Math.round(((b - a) / a) * 100)
  let diff = delta > 0 ? `+${delta}%` : `${delta}%`
 
  return `${before} ${arrow} ${after} (${diff})`
}
 
/**
 * Helper for high-res timing. A function is returned that, when invoked,
 * returns the elapsed time.
 *
 * @return {Function} timer
 */
exports.timer = function () {
  let start = process.hrtime()
  return raw => {
    let elapsed = process.hrtime(start)
    return raw ? elapsed : hrtime(elapsed)
  }
}