Skip to content

Commit bf73e15

Browse files
committed
feature: @putout/apply-arrow: handle case when no loc found
1 parent 69eae3a commit bf73e15

File tree

4 files changed

+51
-4
lines changed

4 files changed

+51
-4
lines changed

packages/plugin-apply-arrow/lib/apply-arrow.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
'use strict';
22

3+
const {print} = require('putout');
4+
35
module.exports.report = () => `Use 'Arrow Function' instead of 'Function Declaration`;
46

57
module.exports.match = () => ({
68
'function __a(__args) {return __b}': ({__a, __b}, path) => {
7-
const columnsCount = __b.loc.end.column - __b.loc.start.column;
8-
const linesCount = __b.loc.end.line - __b.loc.start.line;
9-
10-
if (columnsCount > 30 && !linesCount)
9+
if (isToLong(__b))
1110
return false;
1211

1312
const {name} = __a;
@@ -23,3 +22,25 @@ module.exports.match = () => ({
2322
module.exports.replace = () => ({
2423
'function __a(__args) {return __b}': 'const __a = (__args) => __b',
2524
});
25+
26+
function isToLong(__b) {
27+
let columnsCount = 0;
28+
let linesCount = 0;
29+
30+
if (__b.loc) {
31+
columnsCount = __b.loc.end.column - __b.loc.start.column;
32+
linesCount = __b.loc.end.line - __b.loc.start.line;
33+
} else {
34+
const code = print(__b);
35+
const lines = code
36+
.split('\n')
37+
.filter(Boolean);
38+
39+
const [first] = lines;
40+
41+
linesCount = lines.length - 1;
42+
columnsCount = first.length;
43+
}
44+
45+
return columnsCount > 30 && !linesCount;
46+
}

packages/plugin-apply-arrow/test/apply-arrow.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
'use strict';
22

33
const {createTest} = require('@putout/test');
4+
const {operator} = require('putout');
5+
46
const plugin = require('..');
7+
const {getTemplateValues} = operator;
58

69
const test = createTest(__dirname, {
710
plugins: [
@@ -23,3 +26,19 @@ test('putout: apply-arrow: no report: long', (t) => {
2326
t.noReport('long');
2427
t.end();
2528
});
29+
30+
test('putout: apply-arrow: no report: no-loc', (t) => {
31+
const FN = 'function __a(__args) {return __b}';
32+
33+
t.transform('no-loc', {
34+
noLoc: {
35+
report: () => '',
36+
fix: (path) => {
37+
const {__b} = getTemplateValues(path, FN);
38+
delete __b.loc;
39+
},
40+
include: () => [FN],
41+
},
42+
});
43+
t.end();
44+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function equal(a, b) {
2+
return a.type === b.type && a.value === b.value;
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export function equal(a, b) {
2+
return a.type === b.type && a.value === b.value;
3+
}
4+

0 commit comments

Comments
 (0)