Skip to content

Commit

Permalink
fix(replace): fix replace for ternary operators
Browse files Browse the repository at this point in the history
  • Loading branch information
smnhgn committed Apr 21, 2024
1 parent 9e7f576 commit 2b9a56d
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/replace/src/index.js
Expand Up @@ -74,9 +74,10 @@ export default function replace(options = {}) {
if (objectGuards) expandTypeofReplacements(replacements);
const functionValues = mapToFunctions(replacements);
const keys = Object.keys(functionValues).sort(longest).map(escape);
const lookahead = preventAssignment ? '(?!\\s*(=[^=]|:[^:]))' : '';
const lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
const pattern = new RegExp(
`${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
`${lookbehind}${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
'g'
);

Expand Down
@@ -0,0 +1,9 @@
module.exports = {
description: "replaces value inside ternary operators",
options: {
condition: 'first',
exprIfTrue: 'second',
exprIfFalse: 'third',
preventAssignment: true
}
};
3 changes: 3 additions & 0 deletions packages/replace/test/fixtures/form/ternary-operator/input.js
@@ -0,0 +1,3 @@
/* eslint-disable */
condition ? exprIfTrue : exprIfFalse;
console.log(condition, exprIfTrue, exprIfFalse);
@@ -0,0 +1,3 @@
/* eslint-disable */
first ? second : third;
console.log(first, second, third);
8 changes: 8 additions & 0 deletions packages/replace/test/snapshots/form.js.md
Expand Up @@ -87,6 +87,14 @@ Generated by [AVA](https://avajs.dev).
replaced.doSomething()␊
\`);`

## ternary-operator: replaces value inside ternary operators

> Snapshot 1
`/* eslint-disable */␊
first ? second : third;␊
console.log(first, second, third);`

## typescript-declare: doesn't replace lvalue in typescript declare

> Snapshot 1
Expand Down
Binary file modified packages/replace/test/snapshots/form.js.snap
Binary file not shown.

0 comments on commit 2b9a56d

Please sign in to comment.