In JavaScript, it's generally a good idea to use the brace-on-same-line style, i.e.
if( ... ) { ... } else { ... }
because of javascript's policy of automatic semicolon insertion. While it's usually not a problem, it may bite you one day if you use the brace-on-new-line style.
field_vldn
is a strange name - your other functions are named more descriptively, and use the conventionalcamelCase
style - why doesn'tfield_vldn
do the same?Your validation is being done in two places (
field_vldn
and inblankOrSame
). Combine that logic.The logic for comparing the accounts is too complicated. Or, each part of it is simple, but there's too much repetition, and using the
while
loops (two of them even, instead of extracting a function) is very brute-force, when a more generic solution is possible.
For that last point, here's the deal: this is a simple math problem. An account's balance can be expressed as:
$$ f(x) = ax + b $$
where \$x\$ is the number of days, \$a\$ is the daily increment, and \$b\$ is the initial balance.
To figure out when - if ever - the two accounts, \$f{_1}\$ and \$f{_2}\$, will be equal, you simply isolate \$x\$ in \$f{_1}(x) = f{_2}(x)\$:
$$ x = \frac{b{_2} - b{_1}}{a{_1}-a{_2}} $$
If \$x\$ is zero, the accounts are already equal at day 0.
If \$x\$ is negative, the accounts won't ever be equal (unless you go back in time).
If \$x\$ is positive and an integer, the two accounts will end up being exactly equal after \$x\$ days.
If \$x\$ is positive but fractional, you simply round up to the next integer, and that's the number of days it'll take for one account to "overtake" the other.
If \$x\$ is ±Infinity
(which is how JS expresses \$\frac{n}{0}\$, and which you can check with Number.isFinite()
) the two balances will progress in parallel, and will never be equal or intersect. However, you'll have to do an extra check to see if their initial balances are equal.
If \$x\$ is NaN
, the two accounts are identical (\$x = \frac{0}{0}\$) and will always be equal.
Note that while you can simply use x === Infinity
instead of !Number.isFinite()
, you can't use x === NaN
or x == NaN
. In JavaScript NaN
isn't equal to anything - it's not even equal to NaN
(don't ask why).
You can also calculate the numerator and denominator of the fraction separately, and do some checks there instead of doing the division. Once you have the mathematical approach, you can make some practical optimizations.