Amy Blankenship
1 min readMar 10, 2024

--

I think you actually are completely missing some things about how and why you'd use FP for something like this.

Imagine, instead, you have a form-based application where a user can often enter two dates. The rules can change based on what form you're on, and sometimes they can change based on other data in the form.

So let's say you create some factory functions that return functions that encapsulate the rules. I'll leave the implementation to your imagination, but you could have a createDate1ShouldBeBeforeDate2, createDateShouldNotBeNull, createDatesMustBeWithinRange.

Now, when you go into a form, you can flexibly create your rules:

// typescript
const validators = [
createDateShouldNotBeNull(2, 'due date cannot be null),
createDate1ShouldBeBeforeDate2('due date must be after start date'),
createDatesShouldBeWithinRange(30, 'due date cannot be more than 30 days after start date')
]
const validateDates = (date1, date2, validators) => return validators.reduce((result, validator) => {
const errorMsg = validator(date1, date2)
if (errorMsg) result.push(errorMsg)
return result
}, [])

Now you have a really flexible validation system that you can change at will, just by recreating the array as conditions change.

--

--

Amy Blankenship
Amy Blankenship

Written by Amy Blankenship

Full Stack developer at fintech company. I mainly write about React, Javascript, Typescript, and testing.

Responses (2)