Selectively replace multiple instances of a character within a string: Difference between revisions
Selectively replace multiple instances of a character within a string (view source)
Revision as of 12:43, 28 July 2022
, 1 year ago→{{header|JavaScript}}: Added a variant – expressed in terms of a map-accumulation.
(Add JavaScript) |
(→{{header|JavaScript}}: Added a variant – expressed in terms of a map-accumulation.) |
||
Line 184:
[2, "r", "F"], // the second 'r' with 'F'
])
);</lang>
</lang>▼
{{out}}
<pre>AErBcadCbFD</pre>
AErBcadCbFD▼
Or, expressed as a map-accumulation:
<lang javascript>(() => {
"use strict";
const main = () => {
const
s = "abracadabra",
subs = {
a: "AB CD",
b: "E",
r: " F"
};
return mapAccumL(a => c => {
const
i = (a[c] || 0),
ds = subs[c];
return [
Object.assign(a, {[c]: 1 + i}),
(ds && ds[i]) ? (
ds[i].trim() || c
) : c
];
})({})([...s])[1].join("");
};
// --------------------- GENERIC ---------------------
// mapAccumL :: (acc -> x -> (acc, y)) -> acc ->
// [x] -> (acc, [y])
const mapAccumL = f =>
// A tuple of an accumulation and a list
// obtained by a combined map and fold,
// with accumulation from left to right.
acc => xs => [...xs].reduce(
([a, bs], x) => second(
v => bs.concat(v)
)(
f(a)(x)
),
[acc, []]
);
// second :: (a -> b) -> ((c, a) -> (c, b))
const second = f =>
// A function over a simple value lifted
// to a function over a tuple.
// f (a, b) -> (a, f(b))
([x, y]) => [x, f(y)];
return main();
▲})();</lang>
{{Out}}
▲<pre>AErBcadCbFD</pre>
=={{header|Julia}}==
|