Skip to content

Commit ee8b432

Browse files
authored
fix(replace): ternary operator replacement (#1712)
1 parent 3b0a717 commit ee8b432

File tree

6 files changed

+26
-2
lines changed

6 files changed

+26
-2
lines changed

packages/replace/src/index.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,10 @@ export default function replace(options = {}) {
7474
if (objectGuards) expandTypeofReplacements(replacements);
7575
const functionValues = mapToFunctions(replacements);
7676
const keys = Object.keys(functionValues).sort(longest).map(escape);
77-
const lookahead = preventAssignment ? '(?!\\s*(=[^=]|:[^:]))' : '';
77+
const lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
78+
const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
7879
const pattern = new RegExp(
79-
`${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
80+
`${lookbehind}${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
8081
'g'
8182
);
8283

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = {
2+
description: "replaces value inside ternary operators",
3+
options: {
4+
condition: 'first',
5+
exprIfTrue: 'second',
6+
exprIfFalse: 'third',
7+
preventAssignment: true
8+
}
9+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/* eslint-disable */
2+
condition ? exprIfTrue : exprIfFalse;
3+
console.log(condition, exprIfTrue, exprIfFalse);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/* eslint-disable */
2+
first ? second : third;
3+
console.log(first, second, third);

packages/replace/test/snapshots/form.js.md

+8
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,14 @@ Generated by [AVA](https://avajs.dev).
8787
replaced.doSomething()␊
8888
\`);`
8989

90+
## ternary-operator: replaces value inside ternary operators
91+
92+
> Snapshot 1
93+
94+
`/* eslint-disable */␊
95+
first ? second : third;␊
96+
console.log(first, second, third);`
97+
9098
## typescript-declare: doesn't replace lvalue in typescript declare
9199

92100
> Snapshot 1
68 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)