function secondsFromDuration()

in lib/config/normalizers.js [169:236]


function secondsFromDuration(
  duration,
  defaultUnit,
  allowedUnits,
  allowNegative,
  key,
  logger,
) {
  let val;
  let unit;
  if (typeof duration === 'string') {
    let match;
    if (allowNegative) {
      match = /^(-?\d+)(\w+)?$/.exec(duration);
    } else {
      match = /^(\d+)(\w+)?$/.exec(duration);
    }
    if (!match) {
      return null;
    }
    val = Number(match[1]);
    if (isNaN(val) || !Number.isFinite(val)) {
      return null;
    }
    unit = match[2];
    if (!unit) {
      logger.warn(
        'units missing in duration value "%s" for "%s" config option: using default units "%s"',
        duration,
        key,
        defaultUnit,
      );
      unit = defaultUnit;
    }
    if (!allowedUnits.includes(unit)) {
      return null;
    }
  } else if (typeof duration === 'number') {
    if (isNaN(duration)) {
      return null;
    } else if (duration < 0 && !allowNegative) {
      return null;
    }
    val = duration;
    unit = defaultUnit;
  } else {
    return null;
  }

  // Scale to seconds.
  switch (unit) {
    case 'us':
      val /= 1e6;
      break;
    case 'ms':
      val /= 1e3;
      break;
    case 's':
      break;
    case 'm':
      val *= 60;
      break;
    default:
      throw new Error(`unknown unit "${unit}" from "${duration}"`);
  }

  return val;
}