Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix edge cases with comments
Browse files Browse the repository at this point in the history
lionel-rowe committed May 9, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 9fda7f7 commit 2f40205
Showing 3 changed files with 30 additions and 15 deletions.
33 changes: 19 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
@@ -4,6 +4,10 @@
var found = function (n) {
return n !== -1;
};
/** @param {number} n */
var notFoundGoesLast = function (n) {
return found(n) ? n : Infinity;
};

/** @param {unknown} fn */
module.exports = function isArrowFunction(fn) {
@@ -23,30 +27,31 @@ module.exports = function isArrowFunction(fn) {
var paren = fnStr.indexOf('(');
var brace = fnStr.indexOf('{');
var arrow = fnStr.indexOf('=>');
var slash = fnStr.indexOf('/');

if (classRe.test(fnStr)) {
return false;
}
if (!found(arrow) || !found(firstNonSpace)) {
if (!found(firstNonSpace) || !found(arrow) || classRe.test(fnStr)) {
return false;
}
if (!found(brace) || !found(paren)) {
if (!found(brace) || !found(paren) || paren === firstNonSpace) {
return true;
}
if (found(quote) && quote === firstNonSpace) {
return false;
}
if (paren === firstNonSpace) {
return true;
}
if (Math.min(arrow, brace, paren) === arrow) {

var firstPunct = [
arrow,
brace,
paren,
slash
].map(notFoundGoesLast).sort(function (a, b) {
return a - b;
})[0];

if (firstPunct === arrow) {
return true;
}

var beforeParams = fnStr.slice(0, paren).replace(stripRe, '');
if (beforeParams && beforeParams !== 'async') {
return false;
}

return paren < arrow && arrow < brace;
return !beforeParams || beforeParams === 'async';
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -11,7 +11,7 @@
"test": "npm run tests-only && npm run test:harmony",
"posttest": "npx aud --production",
"tests-only": "nyc tape test",
"test:harmony": "nyc node --es-staging --harmony test",
"test:harmony": "nyc node --harmony test",
"lint": "eslint ."
},
"repository": {
10 changes: 10 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -349,5 +349,15 @@ test('corner cases', function (t) {
'() => {}'() {}
})['() => {}']));

t.ok(isArrowFunction(/* function */x => { }));
t.ok(isArrowFunction(x/* function */ => { }));
t.ok(isArrowFunction(/* function */() => { }));
t.ok(isArrowFunction(()/* function */ => { }));
t.ok(isArrowFunction((/* function */) => {}));

t.notOk(isArrowFunction(function/* => */() { }));
t.notOk(isArrowFunction(function name/* => */() { }));
t.notOk(isArrowFunction(function/* => */name() { }));

t.end();
});

0 comments on commit 2f40205

Please sign in to comment.