Selectively replace multiple instances of a character within a string: Difference between revisions
Content added Content deleted
(Add JavaScript) |
(→{{header|JavaScript}}: Added a variant – expressed in terms of a map-accumulation.) |
||
Line 184: | Line 184: | ||
[2, "r", "F"], // the second 'r' with 'F' |
[2, "r", "F"], // the second 'r' with 'F' |
||
]) |
]) |
||
); |
);</lang> |
||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
<pre>AErBcadCbFD</pre> |
||
⚫ | |||
</pre> |
|||
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(); |
|||
⚫ | |||
{{Out}} |
|||
⚫ | |||
=={{header|Julia}}== |
=={{header|Julia}}== |