Are these JS conditional statements functionally equivalent? - javascript

Regarding conditional if/else statements, are the following examples functionally equivalent?
function isEntering() {
if (this.stage === 'entering') {
return true;
} else {
return false;
}
}
function isEntering() {
if (this.stage === 'entering') {
return true;
} return false;
}
function isEntering() {
if (this.stage === 'entering') {
return true;
}
}
isEntering = (this.stage === 'entering') ? true : false;
If so, I'd use the most terse of the options. But only if the four are functionally equivalent.

If expr is a boolean expression, as it is here, then there is no need to write
if (expr) return true;
else return false;
or to write
if (expr) x = true;
else x = false;
or to ever write
expr ? true : false
because being a boolean expression, expr can be returned, or assigned, directly:
return expr;
x = expr;
The tersest alternative is one you didn't give:
function isEntering() { return this.stage === 'entering'; }

They are not all equivalent.
The first two are equivalent, but:
function isEntering() {
if (this.stage === 'entering') {
return true;
}
}
Would return undefined if this.stage !== 'entering'.
Also:
isEntering = (this.stage === 'entering') ? true : false;
Is not defining a function as the other examples.
As mentioned you can add:
isEntering = () => this.stage === 'entering';
If you don't need a function you can use:
isEntering = this.stage === 'entering'

Related

can we validate multiple functions inside if condition with AND operator using java script is there any other way to check multiple functions true?

I have added these functions and need return something based which function is returning true but it is not working.
//this is function1/
function A() {
return true;
}
function B() {
return true;
}
function C() {
if ({
{
var -customJS - page_type_lookup
}
} === 'product') {
var config = document.querySelector('#product-content > div.product-variations.clearfix > div.attribute.variant-dropdown > div.attribute-values-section > div.label.va-navSectionalOrientation').innerText;
if (config.includes('Sectional Orientation')) {
return true;
} else {
return false;
}
}
}
if (A() === true && B() === true && C() === true) {
return 'A+ Content, RTA Product, Sectional Configurator';
} else if (A() === true && B() === true) {
return 'A+ Content, RTA Product';
} else if (B() === true && C() === true) {
return 'RTA Product, Sectional Configurator';
} else if (C() === true && A() === true) {
return 'Sectional Configurator, A+ Content';
} else if (A() === true) {
return 'A+ Content';
} else if (B() === true) {
return 'RTA Product';
} else {
return 'Sectional Configurator';
}
}
If you have more than one function and a data set which reflects the wanted value of each flag, you could take an array for the functions retun values and another for the strings which are filterd and joined for the result.
const
flags = [a(), b(), c()],
result = ['A+ Content', 'RTA Product', 'Sectional Configurator']
.filter((_, i) => flags[i])
.join(', ');

DRY - Typescript. How can I use DRY principles to avoid duplication of these 2 getters

I know that below two getters are duplicates and could be consolidated and written in a better way. Could any one please help me come up with a way to consolidate these:-
isEqual here is a lodash library to compare two objects.
state in here is an injected state which I am picking the objects from.
public get isUpperModified(): boolean {
if (!this.isUpperAvailable) {
return false;
}
if (
(this.orders.upperPreference.type === '1' &&
this.state.fetchedData.upperPreference.type === '1') ||
(this.orders.upperPreference.type === 'UPPER' &&
this.state.fetchedData.upperPreference.type === 'UPPER')
) {
return false;
}
if (!isEqual(this.orders.upperPreference, this.state.fetchedData.upperPreference)) {
return true;
}
return false;
}
public get isLowerModified(): boolean {
if (!this.isLowerAvailable) {
return false;
}
if (
(this.orders.lowerPreference.type === '1' &&
this.state.fetchedData.lowerPreference.type === '1') ||
(this.orders.lowerPreference.type === 'LOWER' &&
this.state.fetchedData.lowerPreference.type === 'LOWER')
) {
return false;
}
if (!isEqual(this.orders.lowerPreference, this.state.fetchedData.lowerPreference)) {
return true;
}
return false;
}
There are more than 1 way to achieve this.
You can create a new function isModified(type: string) and pass upper or lower as an argument.
Hope this helps
public get isUpperModified(): boolean {
return this.isModified('upper');
}
public get isLowerModified(): boolean {
return this.isModified('lower');
}
private isModified(type: 'lower' | 'upper'): boolean {
const available = type === 'lower' ? this.isLowerAvailable : this.isUpperAvailable;
const order = type === 'lower' ? this.orders.lowerPreference : this.orders.upperPreference;
const state = type === 'lower' ? this.state.fetchedData.lowerPreference : this.state.fetchedData.upperPreference;
if (!available) {
return false;
}
if (
(order.type === '1' &&
state.type === '1') ||
(order.type === type.toUpperCase() &&
state.type === type.toUpperCase())
) {
return false;
}
if (!isEqual(order, state)) {
return true;
}
return false;
}
I would do it something like this
public get isModified(type: 'lower' | 'upper'): boolean {
const isAvailable = type === "lower" ? this.isLowerAvailable : this.isUpperAvailable
const preference = type === "lower" ? "lowerPreference" : "upperPreference";
if (!isAvailable) {
return false;
}
if (
(this.orders[preference].type === '1' &&
this.state.fetchedData[preference].type === '1') ||
(this.orders[preference].type === 'LOWER' &&
this.state.fetchedData[preference].type === 'LOWER')
) {
return false;
}
if (!isEqual(this.orders[preference], this.state.fetchedData[preference])) {
return true;
}
return false;
}
Then while calling this method
use isModified("upper") instead of isUpperModified
and
use isModified("lower") instead of isLowerModified

Shorthand JS Condition

I need a bit of assistance with this shorthand condition. My attempt at it so far is becoming a bit of a challenge and cant seem to make it more readable. I believe it was short circuited from minifying.
if (a === !0 || perSearch.rates.fy2) {
e();
} else if ( perSearch.rates.fy1.multiple || perSearch.rates.fy2.multiple ){
calculateRates();
} else {
perSearch.rates.fy1.multiple;
}
From this terse expression:
a === !0 || (perSearch.rates.fy2 ? perSearch.rates.fy1.multiple || perSearch.rates.fy2.multiple ? e() : calculateRates() : perSearch.rates.fy1.multiple ? e() : calculateRates())
Your expression corresponds to
if (a === !0) {
} else {
if (perSearch.rates.fy2) {
if (perSearch.rates.fy1.multiple || perSearch.rates.fy2.multiple) {
e();
} else {
calculateRates();
}
} else {
if (perSearch.rates.fy1.multiple) {
e();
} else {
calculateRates();
}
}
}
which can be simplified to
if (a !== true) {
if (perSearch.rates.fy1.multiple || (perSearch.rates.fy2 && perSearch.rates.fy2.multiple)) {
e();
} else {
calculateRates();
}
}
This should be it:
if (a !== false) {
if (perSearch.rates.fy2) {
if (!perSearch.rates.fy1.multiple) {
if (perSearch.rates.fy2.multiple) {
e()
}
else {
calculateRates()
}
}
}
else {
if (perSearch.rates.fy1.multiple) {
e()
}
else {
calculateRates()
}
}
}
Is this a return of some sort (return a || result), or a large conditional (a is true or this other code evaluates true)?. Either way I would tend to attack it in stages, block code, then abstract, repeat until the code looks manageable.
Block
Block out your conditionals to make it easier to read.
(
a === !0
|| (
perSearch.rates.fy2
? (perSearch.rates.fy1.multiple || (perSearch.rates.fy2.multiple ? e() : calculateRates()))
: (perSearch.rates.fy1.multiple ? e() : calculateRates())
)
)
Abstract
Abstract out some any big easy repetitions of logic.
const x = rates => ( (rates) ? e() : calculateRates() );
(
a === true || (perSearch.rates.fy2)
? ((perSearch.rates.fy1.multiple) || x(perSearch.rates.fy2.multiple))
: x(perSearch.rates.fy1.multiple)
)
Continue
Work into the code to separate out the conditionals.
const calc = rates => ((rates) ? e() : calculateRates());
const compare = rates => {
let fy1 = (rates.hasOwnProperty('fy1')) ? rates.fy1 : false;
let fy2 = (rates.hasOwnProperty('fy2')) ? rates.fy2 : false;
if (fy2) {
if (fy1.multiple) {
return fy1.multiple;
}
return calc(fy2.multiple);
} else {
return calc(fy1.multiple);
}
}
a === true || compare(perSearch.rates);
Edit (more continue!)
Looking at this again I think it would benefit from some early returns.
Look at conditional for simplification.
If fy2 and if fy1.multiple {return fy1.multiple}
If not fy2 {return fy1.multiple}
If fy2 and not fy1.multiple {return fy2.multiple}
const calc = rates => ((rates) ? e() : calculateRates());
const compare = rates => {
let fy1 = (rates.hasOwnProperty('fy1')) ? rates.fy1 : false;
let fy2 = (rates.hasOwnProperty('fy2')) ? rates.fy2 : false;
// consolidate conditions leading to same place.
if (!fy2 || (fy2 && fy1 && fy1.multiple)) {
return calc(fy1.multiple);
}
return calc(fy2.multiple);
}
a === true || compare(perSearch.rates);

Return True or False Without the OR operator

I need to write a function called "or".
The instruction was:
Given 2 boolean expressions, "or" returns true or false, corresponding to the || operator.
Notes:
* Do not use the || operator.
* Use ! and && operators instead.
Here's my function:
function or(expression1, expression2) {
if(expression1 && !expression2) {
return true;
} else {
return false;
}
}
var output = or(true, false);
console.log(output); // --> IT MUST RETURN true;
Any idea what am I doing wrong?
try this:
function or(a, b) {
return !(!a && !b)
}
Update your code to following
function or(expression1, expression2) {
if(!expression1 && !expression2) {
return false;
} else {
return true;
}
}
function or(expression1, expression2) {
return !(!expression1 && !expression2);
}
console.log(or(true, false)); // --> IT MUST RETURN true;
console.log(or(true, true));
console.log(or(false, false));

Simple isEven function throws syntax error

I can't figure out why this function code will not run? Here is my code.
function isEven(n) {
if (n%2 == 0) {
return true;
};
else {
return false;
};
};
console.log(isEven(50));
I am getting an error message with the "else" statement.
Bit handy on the semi-colons
Should be
function isEven(n) {
if (n%2 == 0) {
return true;
}
else {
return false;
}
}
console.log(isEven(50));
Could even use
function isEven(n) {
return (n%2 == 0);
}
console.log(isEven(50));

Categories

Resources