All files / array/generator charRange.ts

100% Statements 20/20
100% Branches 9/9
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  5x 5x 87x   5x       2x 2x 29x   2x       7x     1x   13x 2x   11x 2x   9x 2x     7x      
function up(fromChar: number, toChar: number, step: number) {
  const list = [];
  for (let i = fromChar; i <= toChar; i += step) {
    list.push(String.fromCharCode(i));
  }
  return list;
}
 
function down(fromChar: number, toChar: number, step: number) {
  const list = [];
  for (let i = fromChar; i >= toChar; i -= step) {
    list.push(String.fromCharCode(i));
  }
  return list;
}
 
function _charRange(fromChar: number, toChar: number, step: number) {
  return fromChar < toChar ? up(fromChar, toChar, step) : down(fromChar, toChar, step);
}
 
export const charRange = (from: string, to: string, step = 1): string[] => {
 
  if (step <= 0) {
    throw Error('step must be greater than 0');
  }
  if (from.length !== 1) {
    throw Error('from must be a character (length: 1)');
  }
  if (to.length !== 1) {
    throw Error('to must be a character (length: 1)');
  }
 
  return _charRange(from.charCodeAt(0), to.charCodeAt(0), step);
 
};