All files / util/src/strings wordWrap.ts

92.85% Statements 13/14
62.5% Branches 5/8
100% Functions 3/3
100% Lines 12/12

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        1x 19x 1x 19x 19x     1x 3x   3x 3x 3x 3x   3x    
export interface WrapOptions {
  width?: number;
}
 
const lineMap = (line: string) =>
  line.slice(-1) === '\n' ? line.slice(0, line.length - 1).replace(/[ \t]*$/gm, '') : line;
const lineReduce = (acc: string[], line: string) => {
  acc.push(...line.split('\n'));
  return acc;
};
 
export const wordWrap = (str: string, options: WrapOptions = {}): string[] => {
  Iif (!str) return [];
 
  const width = options.width || 50;
  const regexString = '.{1,' + width + '}([\\s\u200B]+|$)|[^\\s\u200B]+?([\\s\u200B]+|$)';
  const re = new RegExp(regexString, 'g');
  const lines = (str.match(re) || []).map(lineMap).reduce(lineReduce, [] as string[]);
 
  return lines;
};