Skip to content

Commit

Permalink
fix(replace): ternary operator replacement (#1712)
Browse files Browse the repository at this point in the history
  • Loading branch information
smnhgn authored Jun 5, 2024
1 parent 3b0a717 commit ee8b432
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* eslint-disable */
condition ? exprIfTrue : exprIfFalse;
console.log(condition, exprIfTrue, exprIfFalse);
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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 ee8b432

Please sign in to comment.