DEV Community

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
 
alvaromontoro profile image
Alvaro Montoro

And as an extra, here is a version in which the checks are also sorted:

const generateReport = checkbook => {
  let current = 0;
  return checkbook.replace(/[^0-9a-z\. \n]/gi, "")
                  .split("\n")
                  .sort((a,b) => {
                    const arrA = a.split(" ");
                    const arrB = b.split(" ");
                    if (arrA.length > arrB.length) {
                      return 1;
                    } else if (arrB.length > arrA.length) {
                      return -1;
                    } else {
                      return parseInt(arrA[0]) > parseInt(arrB[0]) ? 1 : -1;
                    }
                  })
                  .map((val, index) => {
                    current = index === 0 ? val : (current - val.split(" ")[2]).toFixed(2);
                    return index === 0 ? "Original Balance: " + val : val + ` ${current}`;
                  })
                  .join("\n")
                  .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)}`);
}