--- id: 5a23c84252665b21eecc801d title: Split a character string based on change of character challengeType: 5 forumTopicId: 302322 --- ## Description
Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right). Blanks should be treated as any other character (except they are problematic to display clearly). The same applies to commas. For instance, the string:
"gHHH5YY++///\"
should be split as:
["g", "HHH", "5", "YY", "++", "///", "\" ];
## Instructions
## Tests
```yml tests: - text: split should be a function. testString: assert(typeof split == 'function'); - text: split("hello") should return an array. testString: assert(Array.isArray(split("hello"))); - text: split("hello") should return ["h", "e", "ll", "o"]. testString: assert.deepEqual(split("hello"), ["h", "e", "ll", "o"]); - text: split("commission") should return ["c", "o", "mm", "i", "ss", "i", "o", "n"]. testString: assert.deepEqual(split("commission"), ["c", "o", "mm", "i", "ss", "i", "o", "n"]); - text: split("ssss----====llloooo") should return ["ssss", "----", "====", "lll", "oooo"]. testString: assert.deepEqual(split("ssss----====llloooo"), ["ssss", "----", "====", "lll", "oooo"]); - text: split("sssmmmaaammmaaat") should return ["sss", "mmm", "aaa", "mmm", "aaa", "t"]. testString: assert.deepEqual(split("sssmmmaaammmaaat"), ["sss", "mmm", "aaa", "mmm", "aaa", "t"]); - text: split("gHHH5YY++///\") should return ["g", "HHH", "5", "YY", "++", "///", "\\"]. testString: assert.deepEqual(split("gHHH5YY++///\\"), ["g", "HHH", "5", "YY", "++", "///", "\\"]); ```
## Challenge Seed
```js function split(str) { } ```
## Solution
```js function split(str) { const concat = xs => xs.length > 0 ? (() => { const unit = typeof xs[0] === 'string' ? '' : []; return unit.concat.apply(unit, xs); })() : []; const group = xs => groupBy((a, b) => a === b, xs); const groupBy = (f, xs) => { const dct = xs.slice(1).reduce( (a, x) => { const h = a.active.length > 0 ? a.active[0] : undefined, blnGroup = h !== undefined && f(h, x); return { active: blnGroup ? a.active.concat([x]) : [x], sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) }; }, { active: xs.length > 0 ? [xs[0]] : [], sofar: [] } ); return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []); }; const map = (f, xs) => xs.map(f); const stringChars = s => s.split(''); return map(concat, group(stringChars(str))); } ```