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;
}
}
Related
I am having a extension where it can notify about new items added to RSS feed reader
All works in v2, but v3 I am unable to load jquery into service worker, since chrome doesnt allow.
As a workaround I have added as module
"background": {
"service_worker": "js/background.js","type": "module"
},
But still its a issue and says ReferenceError: $ is not defined
at Object.parseFeed
Or is there a way I can tweak my code to read xml without jquery?
import $ as module from 'js/jquery-2.1.4.min.js';
var Storage = (function() {
return {
getFeeds: function(callback, returnArray, sortArray) {
returnArray = typeof returnArray !== 'undefined' ? returnArray : true;
sortArray = typeof sortArray !== 'undefined' ? sortArray : true;
chrome.storage.sync.get(function(dataObject) {
var result = dataObject;
if (returnArray) {
var feedArray = this.parseDataObjectIntoArray(dataObject);
result = sortArray ? this.sortArrayOfObjects(feedArray, 'position') : feedArray;
} else {
delete result['RssR:Settings'];
}
callback(result)
}.bind(this));
},
getFeedByUrl: function(feedUrl, callback) {
chrome.storage.sync.get(feedUrl, function(feedData) {
callback(feedData[feedUrl]);
});
},
removeFeedByUrl: function(feedUrl) {
chrome.storage.sync.remove(feedUrl);
},
saveFeedData: function(feedData) {
var saveFeed = {};
saveFeed[feedData.url] = feedData;
this.setDataObject(saveFeed);
},
parseDataObjectIntoArray: function(object) {
var array = [];
Object.keys(object).forEach(function(objectKey) {
if (objectKey.indexOf('RssR:Settings') !== 0) {
array.push(object[objectKey]);
}
});
return array;
},
sortArrayOfObjects: function(array, sortKey) {
array.sort(function(a, b) {
if (typeof a[sortKey] === 'undefined') {
return true;
} else if (typeof b[sortKey] === 'undefined') {
return false;
}
return a[sortKey] - b[sortKey];
});
return array;
},
clearAllData: function() {
chrome.storage.sync.clear();
},
setDataObject: function(dataObject) {
chrome.storage.sync.set(dataObject);
}
}
}());
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
function msToTime(ms) {
let seconds = (ms / 1000).toFixed(1);
let minutes = (ms / (1000 * 60)).toFixed(1);
let hours = (ms / (1000 * 60 * 60)).toFixed(1);
let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) return seconds + " Sec";
else if (minutes < 60) return minutes + " Min";
else if (hours < 24) return hours + " Hrs";
else return days + " Days"
}
var FeedService = (function() {
return {
downloadFeed: function(feed) {
if (!feed.url) {
return;
}
console.log(feed.url)
fetch(feed.url)
.then(response => response.text())
.then(xmlString => {
console.log(xmlString)
this.parseFeed(xmlString, feed);
}
)
.then(data => console.log(data))
},
parseFeed: function(rawData, existingFeedData) {
var newFeedData = {};
var $feedEntries = $(rawData).find("entry").length > 0 ? $(rawData).find("entry") : $(rawData).find('item');
var lastUpdate = Date.now()
console.log("Now = " + lastUpdate)
lastUpdate = (existingFeedData && existingFeedData.lastUpdate) || Date.now()
console.log("Last Update = " + lastUpdate)
console.log("existingFeedData = " + JSON.stringify(existingFeedData))
pubDates = [];
$feedEntries.each(function(index, elm) {
pubDates.push(new Date($(elm).find("pubDate").text()).getTime())
if (lastUpdate < new Date($(elm).find("pubDate").text()).getTime()) {
console.log($(elm).find("title").text().substring(0, 20));
chrome.notifications.create(
$(elm).find("link").text(), {
type: "basic",
iconUrl: "../icons/254.png",
title: $(elm).find("title").text(),
message: "(" + msToTime((Date.now() - new Date($(elm).find("pubDate").text()).getTime())) + ") ",
requireInteraction: true
},
function() {}
);
}
}.bind(this));
console.log("Max date = " + Math.max.apply(null, pubDates))
existingFeedData.lastUpdate = Math.max.apply(null, pubDates);
Storage.saveFeedData(existingFeedData);
},
getUrlForFeed: function($feed, feedSettings) {
if (feedSettings.linkType && $feed.find(feedSettings.linkType).length > 0) {
return $feed.find(feedSettings.linkType).text();
} else if ($feed.find('link').length == 1) {
return $feed.find('link').text();
} else {
if ($feed.find('link[rel="shorturl"]').length > 0) {
return $feed.find('link[rel="shorturl"]').attr('href');
} else if ($feed.find('link[rel="alternate"]').length > 0) {
return $feed.find('link[rel="alternate"]').attr('href');
} else if ($feed.find('link[rel="related"]').length > 0) {
return $feed.find('link[rel="related"]').attr('href');
} else {
return $feed.find('link').first();
}
}
},
saveFeed: function(existingFeedData, newFeedData) {
;
},
updateReadStatusOfNewItems: function(oldItems, newItems) {
if (typeof oldItems === 'undefined' || Object.keys(oldItems).length == 0 || Object.keys(newItems).length == 0) {
return newItems;
}
Object.keys(newItems).forEach(function(url) {
if (oldItems[url]) {
newItems[url].unread = oldItems[url].unread;
}
});
return newItems;
},
setNewBadge: function() {
chrome.browserAction.setBadgeText({
text: 'NEW'
});
}
};
}());
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name == 'updateRssFeeds') {
console.log("Called!")
updateRssFeeds();
}
});
chrome.notifications.onClicked.addListener(function(notificationId) {
chrome.tabs.create({
url: notificationId
});
});
chrome.runtime.onInstalled.addListener(onInstall);
function onInstall() {
chrome.runtime.openOptionsPage();
chrome.alarms.create('updateRssFeeds', {
when: 0,
periodInMinutes: 1
});
}
function updateRssFeeds() {
Storage.getFeeds(function(feeds) {
feeds.forEach(function(feed) {
FeedService.downloadFeed(feed);
});
}, true, false)
}
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";
}
}
I am new to nodejs so below is my code, I need to add try-catch blocks for my below code need some help to do this because new to this things, below is my websocket code newly created I need to add try-catch blocks for this , please help me out anyone
var WebSocket = require('ws');
//var Stomp = require('stompjs');
function CustomWebSocketListener(config) {
RED.nodes.createNode(this,config);
var node = this;
node.on('input', function(msg) {
let temp =msg.payload;
let urllist = temp.url;
let urls=[]
if(global.websocket!=null || global.websocket!=undefined){
let connections=global.websocket;
console.log("global")
if(global.isAccessTokenExpired){
for(let k in connections) {
connections[k].close();
connections[k].reconnect=false
console.log('connection closed:::');
}
urls=urllist;
}
else{
for(let i=0;i<urllist.length;i++){
let group=urllist[i].split("/")[7].split("?");
if(!connections[group[0]]){
urls.push(urllist[i])
}
}
}
}
else{
urls=urllist;
}
console.log("urls.length::::"+urls.length)
if(urls.length > 0){
for(let i=0;i<urls.length;i++){
console.log(':::::::for loop:::::::')
console.log('url----'+urls[i])
function connect(urlIndex) {
let ws;
if(urlIndex!=undefined||urlIndex!=null){
ws = new WebSocket(urls[urlIndex]);
}
else{
ws = new WebSocket(urls[i]);
}
ws.index=i;
ws.reconnect=true;
ws.onopen = function() {
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason);
setTimeout(function() {
console.log("onclose ----ws reconnect"+ws.reconnect)
if(ws.reconnect){
console.log("inside if reconnect")
connect(ws.index);
}
}, 30000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
if(global.websocket==null || global.websocket==undefined){
global.websocket={};
console.log(global.websocket)
global.websocket[urls[i]]=ws;
}
else{
global.websocket[urls[i]]=ws;
}
}
connect();
}
}
});
}
RED.nodes.registerType("custom-websocketlistener",CustomWebSocketListener);
}
Thanks for anyone who would help me out with this
you can directly use where you want like this...
try{
//whatever you want
}
catch(e){
//whatever you want
}
In your code you can use like this
try {
RED.nodes.createNode(this, config)
var node = this
node.on('input', function(msg) {
let temp = msg.payload
let urllist = temp.url
let urls = []
if (global.websocket != null || global.websocket != undefined) {
let connections = global.websocket
console.log('global')
if (global.isAccessTokenExpired) {
for (let k in connections) {
connections[k].close()
connections[k].reconnect = false
console.log('connection closed:::')
}
urls = urllist
} else {
for (let i = 0; i < urllist.length; i++) {
let group = urllist[i].split('/')[7].split('?')
if (!connections[group[0]]) {
urls.push(urllist[i])
}
}
}
} else {
urls = urllist
}
console.log('urls.length::::' + urls.length)
if (urls.length > 0) {
for (let i = 0; i < urls.length; i++) {
console.log(':::::::for loop:::::::')
console.log('url----' + urls[i])
function connect(urlIndex) {
let ws
if (urlIndex != undefined || urlIndex != null) {
ws = new WebSocket(urls[urlIndex])
} else {
ws = new WebSocket(urls[i])
}
ws.index = i
ws.reconnect = true
ws.onopen = function() {}
ws.onmessage = function(e) {
console.log('Message:', e.data)
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason)
setTimeout(function() {
console.log('onclose ----ws reconnect' + ws.reconnect)
if (ws.reconnect) {
console.log('inside if reconnect')
connect(ws.index)
}
}, 30000)
}
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket')
ws.close()
}
if (global.websocket == null || global.websocket == undefined) {
global.websocket = {}
console.log(global.websocket)
global.websocket[urls[i]] = ws
} else {
global.websocket[urls[i]] = ws
}
}
connect()
}
}
})
} catch (e) {
console.log(e)
}
}
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.
I am writing async.waterfall in my biz. See code below. When I run the code, I got 'Cannot read property 'Symbol(Symbol.toStringTag)' of undefined', I do think I pass the right param.
function checkDeleteStatus(id) {
const idType = id instanceof Array;
const whereparam = idType ? [[id]] : [id];
let sql = `select status from ${bookingSheet} where id ${idType ? 'in' : '=' } ?`;
func.connPool(sql, whereparam, (err,rows,fields) => {
if(err == null){
let passTag = true;
for(var i = 0; i < rows.length; i++) {
let row = rows[i];
if (row.status == 0) {
passTag = false;
break;
}
}
return (callback)=>{
passTag ? callback(null, id) : callback('No', null);
}
} else {
return (callback)=>{
callback(err, null);
}
}
});
}
function deleteBooking(data, callback) {
let sql = `delete sql`;
func.connPool(sql, [data], (err,rows,fields) => {
if(err==null){
callback(null, data)
} else {
callback(err, null)
}
});
}
......
async.waterfall([checkDeleteStatus(id), deleteBooking], (err, result) => {
if (err) {
res.json({ code: 400, message: err.toString() })
} else {
res.json({ code: 200, message: "Query Successfully", data: result })
}
})
Interesting thing is, when I try to write below for checkDeleteStatus, it will run correctly. Is that mean, return part goes before sql part? I am new for using node.js waterfall, sorry for this kind of dumb question.
function checkDeleteStatus(id) {
const idType = id instanceof Array;
const whereparam = idType ? [[id]] : [id];
let sql = `select status from ${bookingSheet} `;
return (callback)=>{
callback(null, id);
}
}
I know the resone, the function should write like below. return (callback)=> should expend its range.
function checkDeleteStatus(id) {
return (callback)=>{
const idType = id instanceof Array;
const whereparam = idType ? [[id]] : [id];
let sql = `select status from ${bookingSheet} where id ${idType ? 'in' : '=' } ?`;
func.connPool(sql, whereparam, (err,rows,fields) => {
if(err == null){
let passTag = true;
for(var i = 0; i < rows.length; i++) {
let row = rows[i];
if (row.status == 0) {
passTag = false;
break;
}
}
passTag ? callback(null, id) : callback('No', null);
} else {
callback(err, null);
}
});}
}