Skip to content

Commit

Permalink
Fix to reset lastIndex at false result
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Sep 21, 2023
1 parent 4e23a5e commit 6dba078
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,12 @@ export function findAndReplace(tree, list, options) {
}

// It wasn’t a match after all.
if (value !== false) {
if (value === false) {
// False acts as if there was no match.
// So we need to reset `lastIndex`, which currently being at the end of
// the current match, to the beginning.
find.lastIndex = position + 1
} else {
if (start !== position) {
nodes.push({
type: 'text',
Expand Down
28 changes: 28 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/**
* @typedef {import('mdast').Root} Root
*/

import assert from 'node:assert/strict'
import test from 'node:test'
import {findAndReplace} from 'mdast-util-find-and-replace'
Expand Down Expand Up @@ -374,6 +378,30 @@ test('findAndReplace', async function (t) {
)
})

await t.test('should not treat `false` as a match', async function () {
/** @type {Root} */
const tree = {type: 'root', children: [{type: 'text', value: ':1:2:'}]}

findAndReplace(tree, [
/:(\d+):/g,
/**
* @param {string} _
* @param {string} $1
*/
function (_, $1) {
return $1 === '2' ? u('strong', [u('text', $1)]) : false
}
])

assert.deepEqual(tree, {
type: 'root',
children: [
{type: 'text', value: ':1'},
{type: 'strong', children: [{type: 'text', value: '2'}]}
]
})
})

await t.test('should not recurse into a replaced value', async function () {
const tree = u('paragraph', [u('text', 'asd.')])

Expand Down

0 comments on commit 6dba078

Please sign in to comment.