I am working on a project and in the code I added a few if statements. I was then told that I can do it on line and more efficiently. The way I did works perfectly but I need to refactor to get it accepted. Could you please help me out? I have tried ternary operator as you can see in the examples below but it's still not that short
Assuming that we have two arrays arr1 and arr2 and the following code is implemented to check if their lengths.
const hasValArr1 = ():boolean => return arr1.length > 0
const hasValArr2 = ():boolean => return arr2.length > 0
Now the interesting part if statements
const isEmpty():boolean => {
if (!hasValArr1() && !hasValArr2()) return false
else if (hasValArr1() && hasValArr2()) return true
else if (!hasValArr1() && hasValArr2()) return true
else if (hasValArr1() && !hasValArr2()) return true
}
using ternary operator
(!hasValArr1() && !hasValArr2()) ? false
:(hasValArr1() && hasValArr2()) ? true
:(!hasValArr1() && hasValArr2()) ? true
:(hasValArr1() && !hasValArr2()) && true
How would you go to write this in a more readable and efficient way? Thanks in advance!
The implementation does not match the name of the method. The name of the method is isEmpty but it returns false if both arrays don't have a value: if (!hasValArr1() && !hasValArr2()) return false
So the name should be: hasAnyValue or doArraysHaveAnyValue or something of that sorts.
As for simplification, you can simply use ||:
const doArraysHaveAnyValue(): boolean => {
return hasValArr1() || hasValArr2();
}
The reason this is better is that it is easier to read, and gives preference to using "positive" instead of negation with !
I think you can
сonst isEmpty():boolean => {
if (!hasValArr1() && !hasValArr2())
return false
return true;
}
or:
const isEmpty():boolean => {
return (!hasValArr1() && !hasValArr2())
}
or if you want to check whether the both arrays have values:
const HasArraysData():boolean => {
return (hasValArr1() && hasValArr2())
}
and it becomes simpler to read code:
if (HasArraysData)
or:
if (!HasArraysData)
Without questioning the premise of the question, you can write :
const isEmpty():boolean => {
return hasValArr1() || hasValArr2()
}