All files / src/lib time-string-adder.js

100% Statements 25/25
100% Branches 27/27
100% Functions 3/3
100% Lines 22/22
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              6x 86x 86x 3x 86x 86x 86x 10x 76x 66x 9x 9x   66x     6x 86x 86x 86x         76x 76x 76x 10x 66x    
import zeroPad from './zero-pad';
import getGroups from './get-groups';
import getBase from './get-base';
import stringify from './stringify';
import toggle24Hr from './toggle-24-hour';
import isTwelveHourTime from './is-twelve-hour-time';
 
const add = (groups, groupId, amount, twelveHourTime) => {
  var base = getBase(groupId, twelveHourTime);
  if (!groupId && groups[groupId] === '12' && twelveHourTime)
    groups[groupId] = '00';
  var val = Number(groups[groupId]) + amount;
  groups = replace(groups, groupId, (val + base) % base);
  if (groupId && val >= base)
    return add(groups, groupId - 1, 1, twelveHourTime);
  if (groupId && val < 0) return add(groups, groupId - 1, -1, twelveHourTime);
  if (!groupId && twelveHourTime) {
    if (val >= base || val < 0) toggle24Hr(groups);
    if (groups[0] === '00') groups[0] = '12';
  }
  return groups;
};
 
const replace = (groups, groupId, amount) => {
  var digits = groups[groupId].length;
  groups[groupId] = zeroPad(String(amount), digits);
  return groups;
};
 
// export default function adder(str, groupId, amount) {
export default (str, groupId, amount) => {
  var groups = getGroups(str);
  var twelveHourTime = isTwelveHourTime(groups);
  if (twelveHourTime && groupId === groups.length - 1)
    return stringify(toggle24Hr(groups));
  return stringify(add(groups, groupId, amount, twelveHourTime));
};