UNPKG

1.79 kBJavaScriptView Raw
1const { checkRule, hideStack } = require('./lib');
2
3/**
4 * _SyncReplaceable_ function receives the whole string and returns the result of transform rules which are either sync function replacers or string replacements (see https://github.com/artdecocode/restream#rule-type for more info). This is not a class and just a function.
5 * @param {string|!Buffer} input The string or buffer to transform synchronously using the replacements. Does not support asynchronous replacements.
6 * @param {!Array<!_restream.Rule>} rules An array with rules.
7 * @return {string}
8 * @example
9```
10// markdown __ to html <em> implementation
11const stream = SyncReplaceable('__hello world__', {
12 re: /__(\S+)__/g,
13 replacement(match, p1) {
14 return `<em>${p1}</em>`
15 },
16})
17```
18 */
19function SyncReplaceable(input, rules) {
20 /**
21 * @suppress {globalThis}
22 */
23 function replace() {
24 const fr = rules.filter(checkRule)
25 const s = fr.reduce((acc, { re, replacement }) => {
26 /** @type {string} */
27 let Acc = acc
28 if (this._broke) return Acc
29
30 if (typeof replacement == 'string') {
31 Acc = Acc.replace(re, replacement)
32 } else {
33 let commonError
34 const t = Acc.replace(re, (match, ...args) => {
35 commonError = new Error()
36 try {
37 if (this._broke) return match
38 const p = replacement.call(this, match, ...args)
39 return p
40 } catch (e) { // hide stack for sync stack traces
41 hideStack(commonError, e)
42 }
43 })
44 return t
45 }
46 }, `${input}`)
47 return s
48 }
49 replace.brake = () => { replace._broke = true }
50 return replace.call(replace)
51}
52
53module.exports=SyncReplaceable
54
55/**
56 * @suppress {nonStandardJsDocs}
57 * @typedef {import('..').Rule} _restream.Rule
58 */
\No newline at end of file