Selectively replace multiple instances of a character within a string: Difference between revisions
Content added Content deleted
m (→Python) |
(→{{header|JavaScript}}: Tidied.) |
||
Line 232: | Line 232: | ||
"use strict"; |
"use strict"; |
||
// -- INSTANCE-SPECIFIC CHARACTER REPLACEMENT RULES -- |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
// # nthInstanceReplaced :: Dict Char [(Null | Char)] -> |
|||
const nthInstanceReplaced = ruleMap => |
|||
⚫ | |||
// A string defined by replacements specified for |
|||
// the nth instances of various characters. |
|||
⚫ | |||
⚫ | |||
c in ruleMap ? (() => { |
|||
⚫ | |||
i = a[c] || 0, |
|||
ds = ruleMap[c]; |
|||
return [ |
return [ |
||
Object.assign(a, {[c]: 1 + i}), |
Object.assign(a, {[c]: 1 + i}), |
||
i < ds.length ? ( |
|||
ds[i] |
ds[i] || c |
||
) : c |
) : c |
||
]; |
]; |
||
})( |
})() : [a, c]; |
||
⚫ | |||
return mapAccumL(go)({})([...s])[1].join(""); |
|||
⚫ | |||
// ---------------------- TEST ----------------------- |
|||
⚫ | |||
// Instance-specific character replacement rules. |
|||
nthInstanceReplaced({ |
|||
a: ["A", "B", null, "C", "D"], |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
Line 268: | Line 280: | ||
v => [...bs, v] |
v => [...bs, v] |
||
)( |
)( |
||
f(a |
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> |