ESLint warning ES6 consistent-return rule - ecmascript-6

I get an ESLint warning:
Expected to return a value art the end of arrow function ( consistent-return)
errors.details.forEach((error) => {
const errorExists = find(errObj, (item) => { // <== ESLint warning
if (item && item.field === error.path && item.location === location) {
item.messages.push(error.message);
item.types.push(error.type);
return item;
}
});
if (!errorExists) {
errObj.push({
field: error.path,
location: error.location,
messages: [error.message],
types: [error.type]
});
}
});
However if I insert a return
const errorExists = find(errObj, (item) => { // <== ESLint warning
if (item && item.field === error.path && item.location === location) {
item.messages.push(error.message);
item.types.push(error.type);
return item;
}
return; // <== inserted return
});
Then no more warning on this line , but then I get 2 warnings on the inserted return ...
Arrow function expected a return value (consistently-return)
Unnecessary return statement (no-useless-return)
I don't see how to solve correctly this issue ..
any feedback welcome

http://eslint.org/docs/rules/consistent-return says:
This rule requires return statements to either always or never specify values.
When your if-condition is not met, the arrow function will terminate without encountering a return statement, which violates this rule. Your second version violates this rule because your second return does not specify a value, contrary to the first return. The second warning tells you that your additional return statement is redundant.
To make the linter happy, you probably should think about what to properly return from the arrow-function if the condition is not met. I do not know what your find function does exactly, but if it behaves similar to Array.prototype.find you might want to return false at the end of the arrow function. If you need to return undefined in that case, this paragraph from the same page applies:
When Not To Use It
If you want to allow functions to have different return behavior depending on code branching, then it is safe to disable this rule.
EDIT: I previously wrote to have a look at the option treatUndefinedAsUnspecified, but looks like either setting will not help if you need to return undefined in just one of the branches.

the return is correctly inserted, however its value should be given ...
return false;
is the correct value

Related

is there a name for this conditional-checking technique?

so, theres a technique I use in a fair amount of programming languages and projects; and I'm wondering if it has a general, language-agnostic "official" term to describe it.
basically, I nicknamed it "trip switch checking." Its where if you need to check that several variables have specific values, possibly of different types, you first set a boolean to "false" and then in either a loop or several if statements, you check what you need to by setting the boolean to true if any of the other variables don't meet your requirements.
I call it trip-switching because the boolean remains false if the "switch" isn't "tripped," using an analogy from a common safety mechanism on industrial machinery where if something moves too far or gets too close or etc. a physical switch is actually bumped into and it shuts the whole thing down. the idea is not to switch it back off until the obstruction is cleared- the machine cant turn itself back on automatically.
pseudocode example, a function that returns true if the trip switch wasn't hit:
function tripswitchcheck()
{
boolean tripswitch = false
if(idontnwantthis == true)
{
tripswitch = true
}
if(iwantthis == false)
{
tripswitch = true
}
//...etc...basically do stuff to check stuff. if any values are undesired, true the tripswitch.
return !tripswitch
}
It may be bad practice depending on the language and nature of the project, but it works, and that's outside of the scope of this question.
First of all, why would you not just have a positive flag in that example:
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(iwantthis == false)
{
success = false;
}
//...etc...basically do stuff to check stuff. if any values are undesired, falsify success
return success
}
Secondly, why check the conditions if you already know you have failure. Say that we don't have a forward goto in the language, or else, or early returns (or we don't want to return because something else is done based on the success flag before returning):
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(success && iwantthis == false) // if success is false, fall through
{
success = false;
}
if(success && !othercondition()) // likewise
{
success = false;
}
//...etc...
return success
}
There are reasons not to use else if some of the conditions make use of earlier results.
Anyway, this just comes from basic logic and scientific reasoning: we have a hypothesis and look for reasons why it is not true.
The name for it is perhaps "single exit rule" and such: the function exits through a single return statement.

Sammy.js : Partial calling/rendering my html twice

I am new to knockout and sammy. I am implementing SPA using Sammy(router) and KnockOut(binding).
I have below code.
this.get('#/Page/:operation', function (context) {
this.partial('templates/Page1.html', { cache: false }).then(function (content) {
// the first argument to then is the content of the
// prev operation
$('#sammyDiv').html(content);
});
});
When I checked the console it's saying "You cannot apply bindings multiple times to the same element.(…)".
Am I doing anything wrong here?
What's the difference between Partial and Render?
Im guessing you are injecting new html into the parent which has already been bound. You should either be more specific about which divs you are binding too. I.E on apply bindings to the parent div of the html you injected, or clean and reapply bindings. I use both methods throughout my application.
if (isBound("my-div"))
ko.cleanNode(document.getElementById('my-div'));
ko.applyBindings(myModel, document.getElementById('my-div'));
Helper Function:
// Checks if Element has Already been Bound (Stops Errors Occuring if already bound as element can't be bound multiple times)
var isBound = function (id) {
if (document.getElementById(id) != null)
return !!ko.dataFor(document.getElementById(id));
else
return false;
};
I use this check before all my bindings as a safety net.
Thanks for the response and comments. Issue was with Sammy router.
this.get('#/Page/:operation', function (context) {
this.partial('templates/Page1.html', { cache: false }).then(function (content) {
// the first argument to then is the content of the
// prev operation
$('#sammyDiv').html(content);
});
});
changed to
this.get('#/Page/:operation', function (context) {
this.partial('templates/Page1.html', { cache: false });
});
It worked perfectly fine. Thanks again.

json.parse and ajax was working ok. until when i set my database online

The json.parse method was working fine . but when i host database in web hosting . it takes me
JSON.parse: unexpected character at line 1 column 1 of the JSON data
this is my code :
function getListProduitsByIdcat(id)
{
$j.get("/java 2015 v0/admin/code%20php/code_produits.php?idca="+id,function(data,status)
{
for(var i=0;i<data.length;i++)
list=[];
list=JSON.parse(data);
names=[];
for(var j=0;j<list.length;j++)
names.push(list[j].nom);
$j("#produit").autocomplete({
source: names,
change: function(event,ui)
{
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$j("#produit").val("");
$j("#produit").attr("placeholder","n'exist pas ");
}
},
focus: function (event, ui) {
return false;
}
});
}
);
}
The error is explicit, Json in data isn't a valid Json. Can you print the data content ?
But I see you didn't check the status, so you don't know if the get method have success or not.
The first for do anything ?
BTW, You have space in your url it's a mistake ?
/java 2015 v0/admin/code%20php/code_produits.php?idca=

Checking whether a checkbox is checked

I have not found any inbuilt function for checking whether a checkbox is set true or false,
isChecked() is not available is apps-script (if i am right).
Any idea on how to find it or we shall have a value change handler to count the number of times the value changed and find if it is checked or not?
You should assign your checkbox a name so that you can retrieve its value in a handler function with e.parameter.checkboxname : this value is boolean.
var chkmode = app.createCheckBox("description").setName("chk1").setId("chk1")
with the ID you can modify its state from the handler function (or from any other) if necessary (getElementbyId())
note that the handler can be on the checkbox itself (a change handler) or on any other element in the UI, depending on your needs.
I might be wrong, however I believe there is a problem with the checkBox status, even though its status looks like boolean, it doesn't behave like boolean but like string
if you print in a spreadsheet e.parameter.myCheckBox you will get TRUE or FALSE
if you print in a spreadsheet e.parameter you will get the whole object and see myCheckBox=true or myCheckBox=false
however, if (e.parameter.myCheckBox) will always return True
the workaround I am using is: if (e.parameter.myCheckBox == "true") will return the actual myCheckBox status
Just in case, I am opening a new ticket in the issue tracker
I hope this would help you
ps. confirmed with Google, e.parameter.myCheckBox is a string, not a boolean
if you want to use it as boolean it would be like (e.parameter.myCheckBox == "true")
var handler = app.createServerClickHandler('tellStatus');
and then (as example showing it in a label)
function tellStatus(e){
var app = UiApp.getActiveApplication();
app.getElementById('yourStatusLabel').setText('Checkbox checked: ' + e.parameter.yourCheckbox)
return app;
}
You should use handler function look like below.
I found example from https://sites.google.com/site/scriptsexamples/learn-by-example/uiapp-examples-code-snippets/check-box
if(e.parameter['checkbox_isChecked_'] == 'true'){
itemsSelected+= e.parameter['checkbox_value_']+',';
}

Checking if an item exists in Action Script

Sorry, I've never done AS before, so I apologize for the basic question. There is a line in this file I am trying to modify:
var media:Namespace = rssXML.channel.item[i].namespace("media");
I'm just trying to check to see if it exists and if it has a value?
I know in PHP it would be
if(isset(rssXML.channel.item[i].namespace("media") && !empty(rssXML.channel.item[i].namespace("media")) {
//Do Something
}
What would be the AS equivalent?
if (variablename) { // it's there } else { // it's not }
All AS classes extend Object which has a hasOwnProperty() test which returns a boolean if a property with the name exists. Then you can test if (property) or if (property == null).
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Object.html#hasOwnProperty()