How do I simplify this expression? - sonarqube

var inventory = [
{ id: 1, name: 'apples', quantity: true },
{ id: 2, name: 'apples', quantity: false },
{ id: 3, name: 'cherries', quantity: true }
];
var result = inventory.find(inv => inv.id === 5) ? true: false;
Sonarqube is suggesting to simplify the expression below -
var result = inventory.find(inv => inv.id === 5) ? true: false;
I have no idea how to simplify it. Can anyone please help to simplify this ?
Sonarqube is suggesting that Boolean literals should not be redundant.

Sonarqube makes a remark that returning a direct boolean value based on condition is just obvious. Consider the following:
if (condition) {
return true;
} else {
return false;
}
or equivalent:
return (condition) ? true : false;
condition itself evaluates to true or false, so it's like saying 'if true then true, if false then false'. Therefore it is just enough to return result of the condition itself, like so:
return (condition);
Now your specific example makes implicit coalescing to a boolean value by using find() return value in a boolean context (implied by ?: operator). Since find() returns undefined when the requested object is not found, your code makes use of falsy value of undefined to resolve ?: to true or false branch. It seems like you are interested in checking whether the value is present in the array, meaning whether find() returns something else than undefined, meaning:
var result = inventory.find(inv => inv.id === 5) !== undefined;

Related

How to convert string Boolean to actual Boolean using kendo-UI data source?

I am trying to convert string boolean to actual boolean, It's not converting properly.
Here is try:
var viewModel = kendo.observable({
Aggregate:true,
qreport:{
aggregateSource: [
{ Name: "viewModel.i18n.QReportCountType", Value: true },
{ Name: "viewModel.i18n.QReportMinMaxType", Value: false }
],
schema: {
model: {
fields: {
Name: { type: "string" },
Value: { type: "boolean" }
}
}
}
}
});
kendo.bind($("#demo"), viewModel);
Hwere is link:
https://dojo.telerik.com/eNakOgIj/13
and in console, it always a convert to string 'true' or 'falsre';
How can I get the true or false value here?
By setting up the value databinding, under the hood it is calling the ObservableObject.Set method (documentation). Unfortunately the only acceptable argument types for the value are Number, String, Date, and Object. Since you are trying to set the value using a type that is not supported, it is implicitly being converted to a String.
This means that you will need to convert the value back to a Boolean when you go to reference it. E.g.
var aggregate = ('' + viewModel.get('Aggregate')).toLowerCase() === 'true';
console.log(aggregate);
Example: https://dojo.telerik.com/AqAtekaF

Angular 2 Custom Validator with Observable Parameter

I have this custom validator:
export const mealTypesValidator = (mealSelected: boolean) => {
return (control: FormControl) => {
var mealTypes = control.value;
if (mealTypes) {
if (mealTypes.length < 1 && mealSelected) {
return {
mealTypesValid: { valid: false }
};
}
}
return null;
};
};
If I use it like this it works:
ngOnInit() {
this.findForm = this.formBuilder.group({
categories: [null, Validators.required],
mealTypes: [[], mealTypesValidator(true)],
distanceNumber: null,
distanceUnit: 'kilometers',
keywords: null,
});
}
The catch is, mealSelected is a property on my component - that changes when the user selects and deselects a meal.
How I call the validator above is using static true which can never change.
How can I get the validator to work when I use the component.mealSelected value as the parameter eg:
ngOnInit() {
this.findForm = this.formBuilder.group({
categories: [null, Validators.required],
mealTypes: [[], mealTypesValidator(this.mealSelected)],
distanceNumber: null,
distanceUnit: 'kilometers',
keywords: null,
});
}
Because if i do it as above, it evaluates this.mealSelected instantly which is false at the time - and then when the user selects a meal, it doesn't then go ahead and pass true into the custom validator.
Solution was to move the validator inside my component and use this.mealSelected to check against. Then I had an issue with the validator not being triggered when a meal was selected/deselected and I used this.findForm.controls['mealTypes'].updateValueAndValidity(); to trigger the validation.
Code (can probably be refactored to remove the parameter from the custom validator):
ngOnInit() {
this.findForm = this.formBuilder.group({
categories: [null, Validators.required],
mealTypes: [[], this.mealTypesValidator(true)],
distanceNumber: null,
distanceUnit: 'kilometers',
keywords: null,
});
}
mealTypesValidator = (mealSelected: boolean) => {
return (control: FormControl) => {
var mealTypes = control.value;
if (mealTypes) {
if (mealTypes.length < 1 && this.mealSelected) {
return {
mealTypesValid: { valid: false }
};
}
}
return null;
};
};
However It would still be nice to be able to have a seperate validation module to centralise validation, so if anyone knows how to have a changing parameter value such as a component field as a parameter to a custom validator - like I initially asked, then I'd appreciate an answer that goes with that technique.

how do I return value to error case in jasmine-mocking a promise?

I am mocking a method that returns value to a promise. I am successful in returning value to positive case but can't seem to return value to negative case. I return value to success case by
return {
then: function (callback) {
return callback({'foo' : "bar"});
}
};
the method I am mocking (below)
login() {
return axios.post("/login");
}
returns control to
login().then((response) => {
console.log("correct",response);
}, (err)=> {
console.log("wrong response",err);
});
Never roll your own thenables like that - that's very risky.
That said, if you must, you can do :
then: function (success, fail) {
return fail(Error("Error"));
};
But why bother? You can do:
return Promise.reject(Error("Error"));
Which is a lot simpler and less error prone, similarly for success:
return Promise.resolve({a: 'a', b: 'b'});

How to know which attribute called the waterline validation rule?

I'm doing my own custom validations on certain fields, so that only certain values are accepted (depending on the field) and the rest rejected. I would like to write a "filter" function that checks what attribute called the validation and from there decide what words the attribute is allowed to use. So the model would look something like this:
module.exports = {
types: {
filter: function(attribute) {
if (attribute === 'number') {
switch(attribute.value) {
case 'one':
return true;
case 'two':
return true;
default:
return false;
}
} else if (attribute === 'color') {
switch(attribute.value) {
case 'red':
return true;
case 'blue':
return true;
default:
return false;
}
}
},
},
attributes: {
number: {
type: 'string',
required: true,
filter: true
},
color: {
type: 'string',
required: true,
filter: true
}
}
};
Of course, in normal Sails.js behaviour, "attribute" would not be the attribute, but the value of the attribute. (And attribute.value was just an example, meaning, I want the attribute value in there).
So, I want attribute to be the actual attribute that called the validation rule. Is this possible with Sails? I mean, I could write a function for each field in the model, but it would be nice to have a function that fits them all (I have many of them).
Thanks.
Ok so I will answer your question, but this may not be exactly what you want. An attribute can have an "enum" which is how we'd achieve your end goal:
attributes: {
state: {
type: 'string',
enum: ['pending', 'approved', 'denied']
}
}
But I will assume that this code is just a contrived example. Here's a way that I think would work.
module.exports = {
types: {
filter: function(attribute) {
if (attribute === 'number') {
switch(attribute.value) {
case 'one':
return true;
case 'two':
return true;
default:
this.validationErrors.push(attribute);
return false;
}
} else if (attribute === 'color') {
switch(attribute.value) {
case 'red':
return true;
case 'blue':
return true;
default:
this.validationErrors.push(attribute);
return false;
}
}
},
},
attributes: {
validationErrors:(function(){
var errors = [];
return {
push:function(attr){
errors.push(attr);
},
get:function(){
return errors;
}
};
})(),
number: {
type: 'string',
required: true,
filter: true
},
color: {
type: 'string',
required: true,
filter: true
}
}
};
Edit:Used an attribute method instead of an attribute
There are potentially a couple problems with this answer. I'm not sure how waterline handles "this" within these custom type functions. Is "this" bound to the model? Or the instance of the model we're creating? There's a lot of questions to be asked here but maybe this can give you some ideas and create a discussion.

additonal parameters for custom_func?

I want to reuse the following code for custom_func:
function validLen(value,colName){
if(value.length === 8){
return [true,""];
}
else{
return [false,"fail"];
}
}
I tried giving it an additional parameter as follows:
function validLen(value,colName,length){
if(value.length === length){
return [true,""];
}
else{
return [false,"fail"];
}
}
And calling it like this:
{name:'cntrct_id', editrules:{custom: true, custom_func:validLen(8)} },
Didn't work. The previous code DOES work, but as stated, I want a reusable function. Is there a workaround for this? Am I doing it wrong?
I would recommend you to use
editoptions: { maxlength: 8}
instead of the custom validation which you use. In the case the input element will be created with the maxlength attribute directly. So the user will not able to type more as characters as specified by maxlength.
UPDATED: You can't change the interface of any callback function, but you can do share common code of different custom_func in the following way. You define your custom validation function having three parameters like
function validLen (value, colName, valueLength) {
if (value.length === valueLength) {
return [true, ""];
}
else {
return [false, "fail"];
}
}
and use it in the following way
{
name: 'cntrct_id',
editrules: {
custom: true,
custom_func: function (value, colName) {
return validLen(value, colName, 8);
}
}
If you need to use this inside of custom_func then you can change return validLen(value, colName, 8); to return validLen.call(this, value, colName, 8);.

Resources