Is there an ESLint rule that limits the number of return statements? - eslint

The rule I'm looking for is(the name is provisional.):
This rule limits the number of return statements in a function.
(The example is ugly, but I expect the following behavior.)
// "max-return-statement-per-function": ["error", 4]
// incorrect
function Foo(str) {
if (str === "a") {
return "a";
} else if (str === "b") {
return "b";
} else if (str === "c") {
return "c";
} else if (str === "d") {
return "d";
} else {
return "others";
}
}
// correct
function Foo(str) {
if (str === "a") {
return "a";
} else if (str === "b") {
return "b";
} else if (str === "c") {
return "c";
} else {
return "others";
}
}

Related

fs.existsSync is not waiting for fs.readFile inside if

if (fs.existsSync('tmp/cache.txt')) {
fs.readFile("tmp/cache.txt", function (err, data) {
if (data != "" || data != "[]") {
jdata = JSON.parse(data);
if (
jdata[jdata.length - 1].substring(4, 8) ==
new Date().getFullYear() + 543
) {
year = new Date().getFullYear() + 542;
console.log("yes this year");
}
jdata.forEach(function (value, i) {
if (
value.substring(4, 8) ==
new Date().getFullYear() + 543
) {
countloveme--;
}
});
jdata.splice(countloveme);
}
});
}
my code is running but
code is finished before fs.readFile inside ifelse have finish
i don't how to add await in fs.readFile or anyway to this code is working
As written in the comments, it would be a better choice to use fs,readFileSync
And when you use Array.forEach() you are starting a new function that is running synchronously.
I've cleared your code maybe this can help you
if (fs.existsSync('tmp/cache.txt')) {
try {
const data = fs.readFileSync("tmp/cache.txt");
if (!data || data != "" || data != "[]")
throw new Error('tmp/cache.txt file is empty');
const jdata = JSON.parse(data);
// More clear to use variables in the if elses
const arg1 = jdata[jdata.length - 1].substring(4, 8)
const arg2 = new Date().getFullYear() + 543;
if (arg1 === arg2) {
// You don't use this date anywhere?
new Date().getFullYear() + 542;
console.log("yes this year");
}
for (let dataChunk of jdata) {
if (
dataChunk.substring(4, 8) ==
new Date().getFullYear() + 543
) {
countloveme--;
}
}
jdata.splice(countloveme);
} catch (error) {
console.error(error.message);
}
}

How can I fix 'Refactor this function to use "return" consistently.' from sonar js

I apply SonarJS analysis to my project.
An error 'Refactor this function to use "return" consistently' was found in the code below.
How can I fix this?
var filter1Depth = function(attr0, attr1, val){
var id;
if(val === "vAuto"){
id = "AirConditioner.Indoor.Ventilator";
val = "Auto";
}
return { // Error is generated from this line.
field : attr0,
operator: function(item, value){
if(value == "") return true;
if(!item || !item.length) return;
var i, length = item.length;
if(value == "undefined"){
for( i = 0; i < length; i++ ){
if(typeof item[i][attr1] === 'undefined'){
return true;
}
}
}else{
for(i = 0; i < length; i++){
if(item[i][attr1] == value){
if(id){
if(id === item[i]["id"]) return true;
return;
}
return true;
}
}
}
return;
},
value : val
};
};
Another example is like below.
var filter1DepthNone = function(attr0, attr1, val){
return { field : attr0, operator: function(item, value){ // error!!
if(value == "") return true;
if(!item || !item.length) return;
var length = item.length;
for(var i = 0; i < length; i++){
if(item[i][attr1] != value){
return;
}
}
return true;
}, value : val};
};
My codes where this error is generated from has similar pattern..
In some blocks, you're returning nothing (return;, so undefined) but in other blocks in the same function, you return a boolean (true/false).
You need to make sure that your returns are consistent within a function - that is, if you return a boolean somewhere, everywhere you return a value within that same function, you also return a boolean.

Typescript generates __awaiter, __generator when using Promises

I'm trying to use nodejs's Promise, my nodejs version is 10.15.3.
I can run this code, but it works strangely when i try to transpile it throw typescript
const p = async () => {
return new Promise((resolve, reject) => {
resolve("Promise works!")
})
}
async function main() {
await p().then(res => console.log(res))
}
main()
Here is output of typescript compiler:
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
var p = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
resolve("Promise works!");
})];
});
}); };
function main() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, p().then(function (res) { return console.log(res); })];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
}
main();
Why does typescript create __awaiter and __generator? My tsconfig.json looks like this:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"noEmitOnError": true,
"importHelpers": true
},
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
UPDATE:
typescript version ^3.4.5
I don't use webpack, pure tsc compiler

Why is Spring Boot so slow in comparison to Node.js and Electron?

I was working on converting a trading applications API calls to Spring boot in order to leverage IB's TWS API. I figured I may as well keep it all in one application. Initially, I was issuing my requests through Angular 2, leveraging Electron. However, when I converted to Spring Boot, I noticed what took a second to return in with Angular and Electron, took upwards of almost seven seconds. I'm having a hard time believing that Java is this slow in comparison to JavaScript. I'm assuming at this point there's a much faster way to do what I'm attempting to do in Java. Any help would be appreciated. Again, I'm simply looking for advice on how to speed things up here, if at all possible.
//Spring Boot Service Layer ---- 7 seconds :-o Seriously....
public List<QuoteResponse> getGapUps(PriceParams p) {
GapUpFilter guf = new GapUpFilter(p);
int payloadSize = 200;
StringBuilder payLoad = new StringBuilder();
String stocks = this.getAllStocks();
String[] sArr = stocks.split(",");
LinkedList<String> ll = new LinkedList<String>( Arrays.asList(sArr));
List<QuoteResponse> qrList = new ArrayList<QuoteResponse>();
while (ll.size() > 0) {
int i = 0;
while (i < payloadSize && ll.size() > 0) {
String stock = ll.pop();
if (stock != null && stock.length() > 0 && ll.size() > 1) {
payLoad.append(stock);
payLoad.append(",");
}
if (stock != null && stock.length() > 0 && ll.size() == 1) {
payLoad.append(stock);
}
i++;
}
QuoteResponseWrapper qrw = this.getPrice(payLoad.toString());
QuoteResponse qr = guf.filterQuote(qrw.getQuoteResponse());
if (qr.getResult().length > 0) {
qrList.add(qr);
}
payLoad = new StringBuilder();
}
return qrList;
}
// Angular, Node.js with Electron - instantaneous
geMarketGaps(stocks: string, pFilter: PriceParams) {
this.securityService.getGaps(stocks).takeUntil(this.ngUnsubscribe).subscribe(lst => {
for (let i = 0; i < lst.quoteResponse.result.length; i++) {
try {
const ppq = new PrePostQuote();
ppq.symbol = lst.quoteResponse.result[i].symbol;
try { ppq.pclose = lst.quoteResponse.result[i].regularMarketPrice.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.cprice = lst.quoteResponse.result[i].regularMarketPrice.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.regularMarketPrice = lst.quoteResponse.result[i].regularMarketPrice.raw; } catch (e) { }
try { ppq.ask = lst.quoteResponse.result[i].ask.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.bid = lst.quoteResponse.result[i].bid.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.shortName = lst.quoteResponse.result[i].shortName; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.sharesOutstanding = lst.quoteResponse.result[i].sharesOutstanding.fmt; } catch (e) { ppq.sharesOutstanding = '0'; }
try { ppq.regularMarketVolume = lst.quoteResponse.result[i].regularMarketVolume.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.averageDailyVolume3Month = lst.quoteResponse.result[i].averageDailyVolume3Month.raw; } catch (e) {
console.log(ppq.symbol, e); }
try { ppq.epsTrailingTwelveMonths = lst.quoteResponse.result[i].epsTrailingTwelveMonths.raw; } catch (e) {
console.log(ppq.symbol, e); }
try { ppq.priceToBook = lst.quoteResponse.result[i].priceToBook.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.askSize = lst.quoteResponse.result[i].askSize.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.bidSize = lst.quoteResponse.result[i].bidSize.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.fullExchangeName = lst.quoteResponse.result[i].fullExchangeName; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.regularMarketDayHigh = lst.quoteResponse.result[i].regularMarketDayHigh.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.regularMarketDayLow = lst.quoteResponse.result[i].regularMarketDayHigh.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.regularMarketOpen = lst.quoteResponse.result[i].regularMarketOpen.raw; } catch (e) {console.log(ppq.symbol, e); }
try { ppq.shortPotential = ppq.getShortPotential(1.2); } catch (e) { }
try {
ppq.marketState = lst.quoteResponse.result[i].marketState;
// console.log('Market State: => ' + ppq.symbol, ppq.marketState);
} catch (e) { }
if (!ppq.marketState) {
continue;
}
try { ppq.regularMarketChangePercent = lst.quoteResponse.result[i].regularMarketChangePercent.raw; } catch (e) { }
try { ppq.pctraw = ppq.regularMarketChangePercent; } catch (e) { console.log(e); }
if (ppq.marketState === 'REGULAR') {
this.marketState = 'Reg Mkt';
}
if ((ppq.marketState === 'POST')
&& lst.quoteResponse.result[i].postMarketPrice) {
try { ppq.cprice = lst.quoteResponse.result[i].postMarketPrice.raw; } catch (e) { console.log(e); }
try { ppq.postMarketChangePercent
= lst.quoteResponse.result[i].postMarketChangePercent.raw; } catch (e) { console.log(e); }
try { ppq.pctgain = lst.quoteResponse.result[i].postMarketChangePercent.fmt; } catch (e) { console.log(e); }
try { ppq.pctraw = ppq.postMarketChangePercent; } catch (e) { console.log(e); }
this.marketState = 'Post Mkt';
}
if ((ppq.marketState === 'PREPRE' || ppq.marketState === 'POSTPOST'
|| ppq.marketState === 'CLOSED') && lst.quoteResponse.result[i].postMarketPrice) {
try { ppq.cprice = lst.quoteResponse.result[i].postMarketPrice.raw; } catch (e) { console.log(e); }
try { ppq.postMarketPrice = lst.quoteResponse.result[i].postMarketPrice.raw; } catch (e) { console.log(e); }
try { ppq.postMarketChangePercent = ppq.getPrePrePctChange(); } catch (e) { console.log(e); }
try { ppq.pctgain = ppq.getPrePrePctChange().toFixed(2) + '%'; } catch (e) { console.log(e); }
try {
ppq.pctraw = ppq.postMarketChangePercent;
if ( ppq.pctraw > 5) {
console.log(ppq.symbol + ' is greater than five percent');
}
} catch (e) { console.log(e); }
this.marketState = 'Post Mkt';
}
if (ppq.marketState === 'PRE' && lst.quoteResponse.result[i].preMarketPrice) {
try { ppq.cprice = parseFloat(lst.quoteResponse.result[i].preMarketPrice.raw); } catch (e) { console.log(e); }
try { ppq.preMarketChangePercent
= parseFloat(lst.quoteResponse.result[i].preMarketChangePercent.raw); } catch (e) { console.log(e); }
try { ppq.pctgain = lst.quoteResponse.result[i].preMarketChangePercent.fmt; } catch (e) { console.log(e); }
try { ppq.pctraw = ppq.preMarketChangePercent; } catch (e) { console.log(e); }
this.marketState = 'Pre Mkt';
}
//////////////////////////////////////////////////////////////////////////////
if (ppq.cprice >= pFilter.minPrice && ppq.cprice <= pFilter.maxPrice) {
if (ppq.pctraw > 0
&& this.activeFilter === 'Market Movers'
&& (ppq.marketState === 'PRE' || ppq.marketState === 'PREPRE' || ppq.marketState === 'POST' || ppq.marketState === 'POSTPOST'
|| ppq.marketState === 'CLOSED'
)
) {
if (ppq.postMarketChangePercent >= pFilter.percent || ppq.preMarketChangePercent >= pFilter.percent ) {
this.quotes.push(ppq);
}
}
//////////////////////////////////////////////////////////////////////////////
if (ppq.pctraw > 0 && this.activeFilter === 'Pct Gainers') {
if (ppq.regularMarketChangePercent >= pFilter.percent) {
this.quotes.push(ppq);
}
}
//////////////////////////////////////////////////////////////////////////////
if (ppq.pctraw < 0 && this.activeFilter === 'Market Losers'
&& (ppq.marketState === 'PRE' || ppq.marketState === 'PREPRE' || ppq.marketState === 'POST'
|| ppq.marketState === 'POSTPOST' || ppq.marketState === 'CLOSED')
) {
if (ppq.postMarketChangePercent <= (pFilter.percent * -1) || ppq.preMarketChangePercent <= (pFilter.percent * -1)) {
this.quotes.push(ppq);
}
}
//////////////////////////////////////////////////////////////////////////////
if (ppq.pctraw < 0 && this.activeFilter === 'Pct Losers') {
if (ppq.regularMarketChangePercent <= (pFilter.percent * -1)) {
this.quotes.push(ppq);
}
}
//////////////////////////////////////////////////////////////////////////////
}
} catch (ex) {
console.log(ex);
}
}
this.recordsProcessed++;
this.securityService.progressStart.next(this.recordsProcessed);
if (this.recordCount === this.recordsProcessed) {
this.showRecs = true;
}
}, error => {
this.recordsProcessed++;
this.securityService.progressStart.next(this.recordsProcessed);
if (this.recordCount === this.recordsProcessed) {
this.showRecs = true;
}
});
}
For anyone who is interested, CompleteableFuture was the solution I employed. I was able to literally pull down over 7MB of JSON in a fraction of the time, literally all quote data for all stock exchanges. By making each request utilize a new thread, the queries ran in parallel, so fast in fact, I had to inject a slight delay in the calls, which laughably is what consumes most of the time. I have to admit, I was of the school of thought that Node.js was certainly faster due to REPL and its non-blocking architecture. However, after taking a deeper dive into the Rabbit hole of Java's multi-threaded abyss, I would strongly caution against such claims.
#Async
public void loadPriceQuotes(String stocks) throws InterruptedException, ExecutionException {
this.currentRecord++;
System.out.println(this.currentRecord + " => " + this.recordCount);
URLUtility urlUtil = new URLUtility();
RestTemplate rt = new RestTemplate();
CompletableFuture.supplyAsync(new Supplier<QuoteResponseWrapper>() {
#Override
public QuoteResponseWrapper get() {
String url = urlUtil.getPriceURL(stocks);
ResponseEntity<QuoteResponseWrapper> response = rt.getForEntity(url, QuoteResponseWrapper.class);
for (Quote q: response.getBody().getQuoteResponse().getResult()) {
SkyWalker.stockQuotes.add(q);
}
return response.getBody();
}
},executor);
return;
}

What is wrong with this script?

var isEven = function(number) {
if (number%2 === 0) {
return true;
};
else if (isNaN(number) === true) {
return ("please input a number");
};
else {
return false;
};
};
Your script should not have the ; behind your closing brackets
Try this:
var isEven = function(number){
if (number%2 === 0) {
return true;
} else if (isNaN(number)===true) {
return ("please input a number");
} else {
return false;
}
}

Resources