| 1 |
import { types as t } from "@babel/core"; |
| 2 |
|
| 3 |
const { |
| 4 |
isObjectProperty, |
| 5 |
isArrayPattern, |
| 6 |
isObjectPattern, |
| 7 |
isAssignmentPattern, |
| 8 |
isRestElement, |
| 9 |
isIdentifier, |
| 10 |
} = t; |
| 11 |
/** |
| 12 |
* This is a helper function to determine if we should create an intermediate variable |
| 13 |
* such that the RHS of an assignment is not duplicated. |
| 14 |
* |
| 15 |
* See https://github.com/babel/babel/pull/13711#issuecomment-914388382 for discussion |
| 16 |
* on further optimizations. |
| 17 |
*/ |
| 18 |
export default function shouldStoreRHSInTemporaryVariable( |
| 19 |
node: t.LVal, |
| 20 |
): boolean { |
| 21 |
if (isArrayPattern(node)) { |
| 22 |
const nonNullElements = node.elements.filter(element => element !== null); |
| 23 |
if (nonNullElements.length > 1) return true; |
| 24 |
else return shouldStoreRHSInTemporaryVariable(nonNullElements[0]); |
| 25 |
} else if (isObjectPattern(node)) { |
| 26 |
const { properties } = node; |
| 27 |
if (properties.length > 1) return true; |
| 28 |
else if (properties.length === 0) return false; |
| 29 |
else { |
| 30 |
const firstProperty = properties[0]; |
| 31 |
if (isObjectProperty(firstProperty)) { |
| 32 |
// the value of the property must be an LVal |
| 33 |
return shouldStoreRHSInTemporaryVariable(firstProperty.value as t.LVal); |
| 34 |
} else { |
| 35 |
return shouldStoreRHSInTemporaryVariable(firstProperty); |
| 36 |
} |
| 37 |
} |
| 38 |
} else if (isAssignmentPattern(node)) { |
| 39 |
return shouldStoreRHSInTemporaryVariable(node.left); |
| 40 |
} else if (isRestElement(node)) { |
| 41 |
if (isIdentifier(node.argument)) return true; |
| 42 |
return shouldStoreRHSInTemporaryVariable(node.argument); |
| 43 |
} else { |
| 44 |
// node is Identifier or MemberExpression |
| 45 |
return false; |
| 46 |
} |
| 47 |
} |