Split a character string based on change of character: Difference between revisions

→‎JS ES6: Updated primitives
(Add Forth solution)
(→‎JS ES6: Updated primitives)
Line 514:
{{Trans|Haskell}}
<lang JavaScript>(() => {
// GENERIC FUNCTIONS ------------------------------------------------------
'use strict';
 
// concat :: [[a]] -> [a] | [String] -> String
// GENERIC FUNCTIONS
const concat = xs =>
xs.length > 0 ? (() => {
const unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
})() : [];
 
// group :: Eq a => [a] -> [[a]]
Line 528 ⟶ 533:
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])
};
Line 543 ⟶ 547:
const intercalate = (s, xs) => xs.join(s);
 
// map :: (a -> b) -> [a] -> [b]
// TEST
const map = (f, xs) => xs.map(f);
return intercalate(", ", group("gHHH5YY++///\\".split(''))
 
.map(x => x.join('')));
// show :: a -> String
const show = (...x) =>
JSON.stringify.apply(
null, x.length > 1 ? [x[0], null, x[1]] : x
);
 
// stringChars :: String -> [Char]
const stringChars = s => s.split('');
 
// TEST -------------------------------------------------------------------
return show(
intercalate(", ",
return intercalate map(", "concat, group(stringChars("gHHH5YY++///\\".split('')))
// TEST )
);
 
// -> "g, HHH, 5, YY, ++, ///, \\"
})();</lang>
 
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
9,659

edits