Today I Learned - Rocky Kev

TIL Avoiding dependencies in your helper functions

POSTED ON:

TAGS:

This is a impure function.

import VALID_VALUES_LIST from './constants';

function isValueValid( value ) {
return VALID_VALUES_LIST.includes( value );
}

Why? Because it NEEDS VALID_VALUES_LIST to work. It depends on it.

One of the super powers of functional programming is pure functions.


function isValueValid( value, validValuesArray = [] ) {
return validValuesArray.includes( value );
}

This is a pure function. You can pass any array in the second param.

Now in your testing library, all of these will work with zero dependencies.

expect( isValueValid( 'hulk', [ 'batman', 'superman' ] ) ).toBe( false );

expect( isValueValid( 'hulk', null ) ).toBe( false );

expect( isValueValid( 'hulk', [] ) ).toBe( false );

expect( isValueValid( 'hulk', [ 'iron man', 'hulk' ] ) ).toBe( true );

VIA
WordPress Block Testing


Related TILs

Tagged:

TIL converting Booleans to Numbers

This helper is great for APIs. Not every language parses true/false the same. But every language knows that 0 is false, and 1 is true.

TIL Avoiding dependencies in your helper functions

Impure functions for helpers? What is this... 1999?

TIL Avoiding dependencies in your helper functions

Impure functions for helpers? What is this... 1999?