O'Reilly logo

Mastering Javascript Functional Programming : Become skilled with Functional Programming in JavaScript by applying Javascript concepts to real world development problems by Federico Kereki

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Testing purified functions

When we considered the roundFix special function, which required using state to accumulate the differences due to rounding, we produced a new version by providing the current state as an added parameter, and by having the function return two values: the rounded one, and the updated state:

const roundFix2 = (a, n) => {    let r = a > 0 ? Math.ceil(n) : Math.floor(n);    a += n - r;    return {a, r};};

This function is now pure, but testing it requires validating not only the returned values but also the updated states. We can base our tests on the experiments we did previously. Once again, we have to use toBeCloseTo() for dealing with floating point numbers but we can use toBe() with integers, which produce no rounding errors: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required