From 373785c729484ffd734a16f6188509f44d232a4a Mon Sep 17 00:00:00 2001 From: Nam Hoang Le Date: Wed, 1 Dec 2021 20:44:15 +0700 Subject: [PATCH] fix: Regexp error in empty column --- src/wrapWord.ts | 4 ++-- test/wrapWord.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/wrapWord.ts b/src/wrapWord.ts index e088e5c..fceeafe 100644 --- a/src/wrapWord.ts +++ b/src/wrapWord.ts @@ -7,7 +7,7 @@ const calculateStringLengths = (input: string, size: number): Array<[Length:numb const chunks: Array<[number, number]> = []; // https://regex101.com/r/gY5kZ1/1 - const re = new RegExp('(^.{1,' + String(size) + '}(\\s+|$))|(^.{1,' + String(size - 1) + '}(\\\\|/|_|\\.|,|;|-))'); + const re = new RegExp('(^.{1,' + String(Math.max(size, 1)) + '}(\\s+|$))|(^.{1,' + String(Math.max(2, size - 1) - 1) + '}(\\\\|/|_|\\.|,|;|-))'); do { let chunk: string; @@ -38,7 +38,7 @@ export const wrapWord = (input: string, size: number): string[] => { const result: string[] = []; let startIndex = 0; - calculateStringLengths(input, size).forEach(([length, offset]) => { + calculateStringLengths(input, Math.max(size, 1)).forEach(([length, offset]) => { result.push(slice(input, startIndex, startIndex + length)); startIndex += length + offset; diff --git a/test/wrapWord.ts b/test/wrapWord.ts index ea875d4..af4828b 100644 --- a/test/wrapWord.ts +++ b/test/wrapWord.ts @@ -23,6 +23,14 @@ describe('wrapWord', () => { expect(wrapWord(stringToRed('aaaaa'), 2)).to.deep.equal(arrayToRed(['aa', 'aa', 'a'])); }); }); + context('empty string', () => { + it('should return empty string as well', () => { + expect(wrapWord('', 0)).to.deep.equal(['']); + expect(wrapWord('', 1)).to.deep.equal(['']); + expect(wrapWord('', 2)).to.deep.equal(['']); + expect(wrapWord('', 3)).to.deep.equal(['']); + }); + }); context('a long word with a special character', () => { it('cuts the word at the special character', () => { expect(wrapWord('aaa\\bbb', 5)).to.deep.equal(['aaa\\', 'bbb']);