-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathcomparison.js
More file actions
36 lines (32 loc) · 1.25 KB
/
comparison.js
File metadata and controls
36 lines (32 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { doc } from 'prettier';
const { group, indent, line } = doc.builders;
const indentIfNecessaryBuilder = (path) => (document) => {
let node = path.getNode();
for (let i = 0; ; i += 1) {
const parentNode = path.getParentNode(i);
if (parentNode.type === 'ReturnStatement') return document;
if (parentNode.type === 'IfStatement') return document;
if (parentNode.type === 'ForStatement') return document;
if (parentNode.type === 'WhileStatement') return document;
if (parentNode.type !== 'BinaryOperation') return indent(document);
if (node === parentNode.right) return document;
node = parentNode;
}
};
export const comparison = {
match: (op) => ['<', '>', '<=', '>=', '==', '!='].includes(op),
print: (node, path, print) => {
const indentIfNecessary = indentIfNecessaryBuilder(path);
const right = [node.operator, line, path.call(print, 'right')];
// If it's a single binary operation, avoid having a small right
// operand like - 1 on its own line
const shouldGroup =
node.left.type !== 'BinaryOperation' &&
path.getParentNode().type !== 'BinaryOperation';
return group([
path.call(print, 'left'),
' ',
indentIfNecessary(shouldGroup ? group(right) : right)
]);
}
};