Selectively replace multiple instances of a character within a string: Difference between revisions

Content added Content deleted
Line 232: Line 232:
"use strict";
"use strict";


// -- INSTANCE-SPECIFIC CHARACTER REPLACEMENT RULES --
const main = () => {
const
s = "abracadabra",
subs = {
a: "AB CD",
b: "E",
r: " F"
};


return mapAccumL(a => c => {
// # nthInstanceReplaced :: Dict Char [(Null | Char)] ->
const nthInstanceReplaced = ruleMap =>
const
i = a[c] || 0,
// A string defined by replacements specified for
ds = subs[c];
// the nth instances of various characters.
s => {
const go = (a, c) =>
c in ruleMap ? (() => {
const
i = a[c] || 0,
ds = ruleMap[c];


return [
return [
Object.assign(a, {[c]: 1 + i}),
Object.assign(a, {[c]: 1 + i}),
ds && ds[i] ? (
i < ds.length ? (
ds[i].trim() || c
ds[i] || c
) : c
) : c
];
];
})({})([...s])[1].join("");
})() : [a, c];

};
return mapAccumL(go)({})([...s])[1].join("");
};

// ---------------------- TEST -----------------------
const main = () =>
// Instance-specific character replacement rules.
nthInstanceReplaced({
a: ["A", "B", null, "C", "D"],
b: ["E"],
r: [null, "F"]
})(
"abracadabra"
);




Line 268: Line 280:
v => [...bs, v]
v => [...bs, v]
)(
)(
f(a)(x)
f(a, x)
),
),
[acc, []]
[acc, []]
Line 281: Line 293:
([x, y]) => [x, f(y)];
([x, y]) => [x, f(y)];



// MAIN --
return main();
return main();
})();</lang>
})();</lang>