calculation of increment value in react js - javascript

I want to pass the parameter value in style for calculate my width. my code is
function getValue(value) {
if (value === 12) {
return {
width: '( 20 - value )%',
};
}
return false;
}
but the width does not working. I am new to react. please help.

You can't calculate if it's a string. Quote marks ('') make it a string. Also, % is a remainder operator. It gets the remainder of two numbers. It's similar to division. You can read more about the remainder operator on MDN
I don't understand what this has to do with react, this is more just vanilla javascript.
I think what you may want is
function getValue(value) {
if (value !== 12) { return false; }
return {
width: (20 - value)/100,
};
}
You could also do the following since it only returns if the value if 12
var getValue = value => value === 12 ? { width: 0.08 } : false
This solution uses arrow functions, auto return, and ternary operators. You can read about them on mdn

You need something like below. You are checking a constant value, so no need to do the arithmetic, just return 8. You can simplify the function as like below
function getValue(value) {
// return object for style or undefined for no styling
return value === 12 ? {'width': '8% !important' } : undefined;
}
If you were to keep the arithmetic because you wanted to just always do a calculation (for instance). Then a nicer way to write out the function would be like this.
function getValue(value) {
return { 'width': `${20 - value}% !important` };
}

Try this
width: (20 - value) + ‘%’

Related

Ag Grid aggregation function with Valuegetter

In AgGrid, I am tyring to use aggregation functions and valuegetter on the same column. It seems that because of valuegetter, my aggreation functions are not working, I just get 0 or null value on aggregation. Could you please check my code for any possible solutions?
Thanks.
{ headerName: "Price", filter: "agNumberColumnFilter", valueGetter: priceValueGetter, allowedAggFuncs: ['avg', 'sum', 'min', 'max']};
function priceValueGetter(params) {
var value = '';
if (params.data) {
var EPrice = params.data.a;
var p1 = params.data.b;
if (EPrice && p1) {
value = (EPrice - p1).toFixed(2);
}
}
return value;
}
Your valueGetter is returning a string.
So the built-in aggregation functions, which expect numbers, are failing.
Try this valueGetter instead:
function priceValueGetter(params): number {
if (params.data && params.data.a && params.data.b) {
return params.data.a - params.data.b
}
return null;
}
This won't format the way that you want, but you can fix that by adding a valueFormatter.
One other piece of advice - given that you have a variable named 'EPrice', I'm assuming that you're dealing with money. You shouldn't depend on Javascript's native 'number' type for money, as it is essentially a 'float', and rounding errors will ensue. There are lots of articles about how to properly handle monetary values in Javascript - I personally use a Javascript port of Java's BigDecimal class, called 'big.js', but there are several other solutions.
Edit - also be careful of using if on a number - it evaluates to false if the number is zero. If that's what you want, fine, but if it isn't, adjust your logic accordingly.

IF condition using string

I am programming in Polymer 1.0 and am trying to create an IF function to change the value of a property. My function is the following:
_searchButton: function(selectednamedropdown, selectedtypedropdown){
if (selectednamedropdown=="no_name_selected" && selectedtypedropdown=="no_type_selected"){
this.searchUsagesBtn = true
} else{
this.searchUsagesBtn = false
}
}
In my mind when selectednamedropdown is equal to "no_name_selected" and selectedtypedropdown is equal to "no_type_selected" the function should set searchUsagesBtn to true and when they are not these values, false.
However, the function does not ever seem to be returning true even when these conditions are met. Any ideas why this might be? Thanks for all help
When I run your function like this:
let searchUsagesBtn;
function search(selectednamedropdown, selectedtypedropdown) {
if (
selectednamedropdown === "no_name_selected" &&
selectedtypedropdown === "no_type_selected"
) {
searchUsagesBtn = true;
} else {
searchUsagesBtn = false;
}
}
search("no_name_selected", "no_type_selected");
console.log("button: ", searchUsagesBtn);
I get button: true in console log. So maybe your inputs in this function are not a strings.
The issue was around how JavaScript treats properties within functions. The function was storing the new value and old value of the first property and not any values of the second property. The solution involved making 2 functions to test the strings in each property. Thanks for all assistance

Angular1/JavaScript - Improve algo condition

I have this condition which verifies the same property labelKey of an object projectType and return of different value according to the value of the property
checkProjectType () {
if (this.projectType.labelKey === 'project_type.rent') {
return 'geographical_area'
} else if (this.projectType.labelKey === 'project_type.buying') {
return 'geographical_area'
} else {
return 'address'
}
}
since there is too much resemblance in the condition how I refactored / optimized the condition with a simplified write using Lodash or ECMAScript 2015 for example ?
You can reduce this to less conditions as per your code.
checkProjectType () {
var labelKey = this.projectType.labelKey;
if (labelKey === 'project_type.rent' || labelKey === 'project_type.buying') {
return 'geographical_area';
}
return 'address';
}
Not sure what you want to do here with lodash
I also don't like if-else-if… chains, so prefer more readable variant.
function checkProjectType() {
const defaultType = 'address';
const key = this.projectType.labelKey;
let map = {
'project_type.rent': 'geographical_area',
'project_type.buying': 'geographical_area'
};
return map[key] || defaultType;
}
map can be defined somewhere else.
Setting an if do X else if do X else do Y is wrong to me, you can simplify that in a single line : if (this.projectType.labelKey === 'project_type.rent' || this.projectType.labelKey === 'project_type.buying') would be easier to read already.
One alternative way this could be written is using a switch statement:
switch (this.projectType.labelKey) {
case 'project_type.rent':
case 'project_type.buying':
return 'geographical_area';
default:
return 'address';
}
But one might argue it's a bit overkill in this case. Lodash or ECMAScript 2015 isn't going to do anything for you here.
You can check if the project type is included in an array of types, and use a ternary to select the response:
checkProjectType() {
return ['project_type.rent', 'project_type.buying'].includes(this.projectType) ? 'geographical_area' : 'address';
}
If the types that produce geographical_area, you can refactored them out of the method (and the object/class):
const geoTypes = ['project_type.rent', 'project_type.buying'];
checkProjectType() {
return geoTypes.includes(this.projectType) ? 'geographical_area' : 'address';
}

jQuery return multiple function

so, i have the following js:
function RHL(a,b,c)
{
return rx.removeClass(a).addClass(b);
return rhpfc.html(parseInt( rhpfc.html() ) -1 );
}
I am having a bit of difficult time with the formatting and syntax.
How do I combine both lines under one return. Also, I want to have two options: -1 or +1. So, I thought I would make - or + as c.
what kind of bracket do I need? (ie. 'c'1)
function RHL(a,b,c){
return [
rx.removeClass(a).addClass(b),
rhpfc.html(parseInt( rhpfc.html() ) -1 )
];
}
then you will need to use the index 0 or 1 to use the return value..
var rx = RHL(a,b,c)[0];
or
var rhpfc = RHL(a,b,c)[1];

lack of identity between jQuery selector and jQuery variable?

I'm running into a maddening problem where I set a variable to point to a jQuery selector, such as: var foobar=jQuery(this); I then pass this variable to a function to be worked on. Let's simplify a little and say the function looks like this:
function SetFieldValue (selector) {
selector.val('test');
console.log ( selector );
console.log ( jQuery('#' + selector.attr('id')) );
}
In this situation if you assume that:
the selector is always a form element (and therefore val() is a valid operation)
the selector does resolve to a single dom element which has an 'id' attribute
You would then expect the two console.log statements to output the same result, right? Well I'm running into a situation where this condition only happens about 90% of the time.
In order to give more context I've created a short screencast demonstrating the problem:
SCREENCAST LINK
For reference purposes, here's the actual SetFieldValue code that is shown in the screencast:
function SetFieldValue ( domObject, value ) {
// as a safety function, check if a string representation of the domObject was passed in and convert it to a jQuery object if it was
if ( jQuery.type(domObject) === "string") {
console.log ("Value passed into SetFieldValue was a string representation so converting to jQuery object");
domObject = jQuery(domObject);
}
if ( jQuery.inArray (domObject.prop('tagName').toLowerCase(),['input' , 'select' , 'textarea']) >= 0 ) {
console.log ("setting to value attribute: " + value);
if ( domObject.hasAttr('id') ) {
domObject.val(value);
//jQuery('#' + domObject.attr('id')).val(value);
} else {
domObject.attr('value',value);
}
console.log ("Using jQuery ID it is set to: " + jQuery('#' + domObject.attr('id')).val() );
console.log ("Using jQuery selector variable it is set to: " + domObject.val() );
} else {
console.log ("setting to html attribute");
domObject.html( value );
}
return domObject;
}
Lets examine the code a bit.
First assigning back to a parameter is not a good practice adding a var at the start of your function would be a lot better, as scope can be lost.
//Suggestion change parameter to domItem
var domObject
Your missing an error handler for when the parameter is not String.
when identifying the type use
<VARNAME>.constructor.toString().match(/function (\w*)/)[1] === "<TYPE>"
It's more efficient and handles custom types.
No need for all the logic in assignment of value attribute. Any dom Object can be made to have a value attribute. also not sure why you are setting the val versus the value.
domObject.attr('value',value);
It is at this point that I can see your code could really use some documentation to help explain purpose
If you are explicitly only wanting to set value on Input fields and set value as innerhtml on non input fields then yes the logic would be needed but could be simplified to ... as the value doesn't need to be detected to overwritten.
if (jQuery.inArray (domObject.prop('tagName').toLowerCase(), ['input' , 'select' , 'textarea']) >= 0) {
domObject.attr('value',value);
} else {
domObject.html( value );
}
No Idea why you are returning the domObject out.
So a quick rewrite without the return and keeping most of the logic adding error handling results in
/*jslint sloppy: true*/
/*global jQuery*/
function SetFieldValue(domString, value) {
// as a safety function, check if a string representation of the domObjects was passed in and convert it to a jQuery object if it was
var domObjects, index;
//errorhandling
if (domString === undefined || domString === null) {
throw {error : "domString must have a value."};
}
if (domString.constructor.toString().match(/function (\w*)/)[1] !== "string") {
if (domString.constructor.toString().match(/function (\w*)/)[1].match(/HTML[a-zA-Z]*Element/) === null) {
throw {error : "domString expected to be String or domObjects"};
}
} else {
if (jQuery(domString).length === 0) {
throw {error : "domString does not resolve to a detectable domObjects."};
}
}
//errorhandling
//action
if (domString.constructor.toString().match(/function (\w*)/)[1].match(/HTML[a-zA-Z]*Element/)) {
//made as an array to normalize as jQuery returns an array allows code to be simplified
domObjects = [domString];
} else {
domObjects = jQuery(domString);
}
//given that domObjects are an array need to step through the array
for (index = domObjects.length - 1; index >= 0; index -= 1) {
if (
jQuery.inArray(
domObjects[index].tagName.toLowerCase(),
['input', 'select', 'textarea']
) >= 0
) {
if (domObjects[index].hasAttr('id')) {
domObjects[index].val(value);
} else {
domObjects[index].attr('value', value);
}
} else {
domObjects[index].html(value);
}
}
}
The above passes JSLint
I know I didn't provide enough context for people to really dig into this problem but I have in the end solved it. What was the issue? Well it was #Kobi who first asked is the DOM element's ID unique ... to which I happily reported it was. And it had been but in fact that WAS the problem. Jesus. It's always the obvious things that you then go onto overlook that get you in trouble.
Anyway, thanks for your patience and help.

Categories

Resources