Split a character string based on change of character: Difference between revisions
Split a character string based on change of character (view source)
Revision as of 18:30, 7 March 2022
, 2 years ago→JavaScript ES6: Added a variant expressed in terms of a general `span` function.
(→JavaScript ES6: Added a variant expressed in terms of a general `span` function.) |
|||
Line 1,406:
}
});
// MAIN ---
return main();
})();</lang>
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Or, in terms of a general `span` function:
<lang javascript>(() => {
"use strict";
// -------- STRING SPLIT ON CHARACTER CHANGES --------
// charGroups :: String -> [String]
const charGroups = s =>
// The characters of s split at each point where
// consecutive characters differ.
0 < s.length ? (() => {
const
c = s[0],
[xs, ys] = span(x => c === x)([
...s.slice(1)
]);
return [
[c, ...xs], ...charGroups(ys)
]
.map(zs => [...zs].join(""));
})() : "";
// ---------------------- TEST -----------------------
// main :: IO()
const main = () =>
charGroups("gHHH5YY++///\\")
.join(", ");
// --------------------- GENERIC ---------------------
// span :: (a -> Bool) -> [a] -> ([a], [a])
const span = p =>
// Longest prefix of xs consisting of elements which
// all satisfy p, tupled with the remainder of xs.
xs => {
const i = xs.findIndex(x => !p(x));
return -1 !== i ? (
[xs.slice(0, i),
xs.slice(i)
]
) : [xs, []];
};
// MAIN ---
|