--- id: 594faaab4e2a8626833e9c3d title: Tokenize a string with escaping challengeType: 5 forumTopicId: 302338 dashedName: tokenize-a-string-with-escaping --- # --description-- Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters: It should output a list of strings. Rules for splitting: Rules for escaping: Demonstrate that your function satisfies the following test-case: Given the string
one^|uno||three^^^^|four^^^|^cuatro|
and using `|` as a separator and `^` as escape character, your function should output the following array:
  ['one|uno', '', 'three^^', 'four^|cuatro', '']
# --hints-- `tokenize` should be a function. ```js assert(typeof tokenize === 'function'); ``` `tokenize` should return an array. ```js assert(typeof tokenize('a', 'b', 'c') === 'object'); ``` `tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')` should return `['one|uno', '', 'three^^', 'four^|cuatro', '']` ```js assert.deepEqual(tokenize(testStr1, '|', '^'), res1); ``` `tokenize('a@&bcd&ef&&@@hi', '&', '@')` should return `['a&bcd', 'ef', '', '@hi']` ```js assert.deepEqual(tokenize(testStr2, '&', '@'), res2); ``` # --seed-- ## --after-user-code-- ```js const testStr1 = 'one^|uno||three^^^^|four^^^|^cuatro|'; const res1 = ['one|uno', '', 'three^^', 'four^|cuatro', '']; // TODO add more tests const testStr2 = 'a@&bcd&ef&&@@hi'; const res2 = ['a&bcd', 'ef', '', '@hi']; ``` ## --seed-contents-- ```js function tokenize(str, sep, esc) { return true; } ``` # --solutions-- ```js // tokenize :: String -> Character -> Character -> [String] function tokenize(str, charDelim, charEsc) { const dctParse = str.split('') .reduce((a, x) => { const blnEsc = a.esc; const blnBreak = !blnEsc && x === charDelim; const blnEscChar = !blnEsc && x === charEsc; return { esc: blnEscChar, token: blnBreak ? '' : ( a.token + (blnEscChar ? '' : x) ), list: a.list.concat(blnBreak ? a.token : []) }; }, { esc: false, token: '', list: [] }); return dctParse.list.concat( dctParse.token ); } ```