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 17:15, 28 July 2022
, 1 year ago→{{header|JavaScript}}: Tidied.
m (→Python) |
(→{{header|JavaScript}}: Tidied.) |
||
Line 232:
"use strict";
// -- INSTANCE-SPECIFIC CHARACTER REPLACEMENT RULES --
const main = () => {▼
const▼
s = "abracadabra",▼
subs = {▼
a: "AB CD",▼
b: "E",▼
r: " F"▼
};▼
// # nthInstanceReplaced ::
const nthInstanceReplaced = ruleMap =>
const▼
// A string defined by replacements specified
// the nth instances of various
▲ const go = (a, c) =>
c in ruleMap ? (() => {
i = a[c] || 0,
ds = ruleMap[c];
return [
Object.assign(a, {[c]: 1 + i}),
ds[i]
) : c
];
})(
};▼
return mapAccumL(go)({})([...s])[1].join("");
// ---------------------- TEST -----------------------
// Instance-specific character replacement rules.
nthInstanceReplaced({
a: ["A", "B", null, "C", "D"],
Line 268 ⟶ 280:
v => [...bs, v]
)(
f(a
),
[acc, []]
Line 281 ⟶ 293:
([x, y]) => [x, f(y)];
// MAIN --
return main();
})();</lang>
|