Refactoring if else statement - javascript

Here is my method:
Object.entries(query).forEach(([key, value]) => {
if (key === 'team_ids') {
if (typeof value === 'string') {
this.items.push(this.$store.getters.teamById(value));
} else {
value.forEach((itemId) => {
this.items.push(this.$store.getters.teamById(itemId));
});
}
else if (key === 'close_ids') {
if (typeof value === 'string') {
this.items.push(this.$store.getters.closeFriendsById(value));
} else {
value.forEach((friendId) => {
this.items.push(this.$store.getters.closeFriendsById(friendId));
});
}
} else {
if (key === 'name') this.name = value;
if (key === 'patr') this.patr= value;
}
});
I am trying to refactor it but now i'm stumped...
It don't looks good.
Any advice?

You can refactor if statements with a switch statement.
Try this:
Object.entries(query).forEach(([key, value]) => {
switch(key) {
case 'name' :
this.name = value; break;
case 'patr' :
this.patr = value; break;
default:
let getterMap = {
'team_ids': 'teamById',
'close_ids': 'closeFriendsById'
}
if(Array.isArray(value)) {
value.forEach((itemId) => {
this.items.push(this.$store.getters[getterMap[key]](itemId));
});
} else {
this.items.push(this.$store.getters[getterMap[key]](value));
}
break;
}
});
You can add more keys in getterMap if you want to.

It's not bad, You have ternary operators which make code cleaner and if statements are shortened. However, to if you want to refactor it, you should provide some info about the logic, because it is important in refactoring.

Related

Double click function not working in the React

I have followed this link https://codesandbox.io/s/25777826onclick-works-but-ondoubleclick-is-ignored-on-react-component-ul6f5?file=/src/App.tsx to create a double-click event. This is simple and works. But if I use this method modification to my code is not working.
This one is a sample double-click function:
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
switch (e.detail) {
case 1:
console.log("click");
break;
case 2:
console.log("double click");
break;
case 3:
console.log("triple click");
break;
}
};
<div className="App">
<button onClick={handleClick}>Click me</button>
</div>
This is my original code:
const popUpHandler = e => {
console.log('popUpHandler', e);
if (e.type === 'Editor') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
const doctorFromDb = response.data.doctor;
if (doctorFromDb.includes('|')) {
setStringOfDoctor(doctorFromDb.split('|'));
} else {
setStringOfDoctor([doctorFromDb]);
}
setAppt(response.data);
});
setOpenUpdatePopup(true);
} else if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
if (e.type === 'DeleteAlert') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
setAppt(response.data);
});
setOpenDeletePopup(true);
}
}
if (e.type === 'QuickInfo' && e.target.classList[0] === 'e-work-cells') {
e.cancel = true;
if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
};
This one is after modification to my code, but is not working:
const popUpHandler = (e: React.MouseEvent<HTMLButtonElement>) => {
switch (e.detail) {
case 1:
console.log('Nothing');
break;
case 2:
if (e.type === 'Editor') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
const doctorFromDb = response.data.doctor;
if (doctorFromDb.includes('|')) {
setStringOfDoctor(doctorFromDb.split('|'));
} else {
setStringOfDoctor([doctorFromDb]);
}
setAppt(response.data);
});
setOpenUpdatePopup(true);
} else if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
if (e.type === 'DeleteAlert') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
setAppt(response.data);
});
setOpenDeletePopup(true);
}
}
if (e.type === 'QuickInfo' && e.target.classList[0] === 'e-work-cells') {
e.cancel = true;
if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
}
};
Hope someone can guide me on how to modify my original code and make it double-click (case 2 is double click). Thank you.

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(', ');

Check data type from string input in JavaScript

I'm trying to get the DataType(?) from string input value.
const data = ['1', 'hello', '[]', '{key: [value]}', '`2020-10-08`'];
function funct(data: string): DataType {
if(??) {
return Object
} else if(??) {
return Number
} else if(??) {
return Array
} else if (??) {
return Date
}
return String
}
data.map((d) => console.log(funct(data)));
// Number, String, Array, Object, Data
function funct(d) {
if(d.startsWith('{') && d.endsWith('}')) {
return typeof {}
} else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
return 'Date';
} else if(!isNaN(parseFloat(d))) {
return typeof 1
} else if(d.startsWith('[') && d.endsWith(']')) {
return typeof []
} else return typeof 'string'
}
console.log('number', funct('1'));
console.log('number', funct('123'));
console.log('string', funct('`as2d`'));
console.log('string', funct('2s2d'));
console.log('Object', funct('{}'));
console.log('Array', funct('[]')); //object :(
console.log('Array', funct('["d", "f"]')); //object :(
You can try something like this:
function funct(d) {
if(d.startsWith('{') && d.endsWith('}')) {
return Object
} else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
return Date;
} else if(!isNaN(parseFloat(d))) {
return Number
} else if(d.startsWith('[') && d.endsWith(']')) {
return Array
} else return String
}
Note: this was tested in JS so, I removed the type annotations. Please them if you want to compile it in TypeScript.

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

Javascript If Condition not evaluating correctly

I have a section of code where a variable contains a particular string (here it's multiply), and when I check if the variable has that particular string, the condition always equates to false. I cannot find what I'm missing here.
// calculations
$scope.$watch('colInput.' + el.key, function () {
angular.forEach($scope.colInput[el.key], function (item, index) {
angular.forEach($scope.column[el.key], function (item_1, index_1) {
if (item.hasOwnProperty(item_1.key)) {
item[item_1.key].type = item_1.type;
item[item_1.key].id = item_1.id;
item[item_1.key].options = item_1.options;
}
else {
item[item_1.key] = {};
item[item_1.key].type = item_1.type;
item[item_1.key].id = item_1.id;
item[item_1.key].options = item_1.options;
}
})
angular.forEach(item, function (elem, key) { //each column of the row
var operand_1, operator, operand_2;
if (elem.type == 10) {
// analyzing the formula
elem.options.forEach(function (el, index) {
if (isNaN(el) && index == 1) {
operator = el;
} else if (isNaN(el) && index == 0) {
operand_1 = el;
} else if (isNaN(el) && index == 2) {
operand_2 = el;
} else if (!isNaN(el)) {
operand_2 = parseFloat(el);
}
})
console.log(operator, eval(operator === "multiply"), typeof operator);
if (operator == 'multiply') {
console.log("IF---")
elem.value = parseFloat(item[operand_1].value) * operand_2;
}
}
})
})
}, true)
It looks like your operator is an HTML element not a String.
The comparison with multiply will always be false.

Categories

Resources