This is going to be one of those "don't do this at home" types of code (or maybe "do it at home but not at work"). I tried to do it as a single chain of commands, assuming that the string is going to be valid. It can be further cleaned and reduced, I'll try later.
Here is the code commented step-by-step:
constgenerateReport=checkbook=>{letcurrent=0;// use regular expressions to remove unwanted charactersreturncheckbook.replace(/[^0-9a-z\.\n]/gi,"")// separate the string into an array splitting by new line.split("\n")// update each value to include the total at the end.map((val,index)=>{current=index===0?val:(current-val.split("")[2]).toFixed(2);returnindex===0?"Original Balance: "+val:val+` ${current}`;})// convert array into string again.join("\n")// concatenate the total and average.concat(`\nTotal expense: ${(checkbook.split("\n")[0]-current).toFixed(2)}`).concat(`\nAverage expense: ${((checkbook.split("\n")[0]-current)/(checkbook.split("\n").length-1)||0).toFixed(2)}`);}
JavaScript
This is going to be one of those "don't do this at home" types of code (or maybe "do it at home but not at work"). I tried to do it as a single chain of commands, assuming that the string is going to be valid. It can be further cleaned and reduced, I'll try later.
Here is the code commented step-by-step:
You can see it working on this CodePen.
And as an extra, here is a version in which the checks are also sorted: