So I have a form handling system set up where I can pass value formatting options that will change the input to fit a certain formatting (for instance stripping non-number values, enforcing max-length, adding hyphens at every X interval etc) and I want to create a function that creates a combined formatter of an arbitrary number of more minute formatters, and runs the value through these in order.
For instance a formatter could be, in the case of numbers only:
const numberFormatter = value => value.replace(.replace(/[^\d]/g, '');
But I also have createFormatter functions, like for max length:
export const createMaxLengthFormatter = (maxLength) => (value) => value
.slice(0, maxLength);
The way I use them is usually like this:
const someNumberInput = createFormField({
...otherParams,
valueFormatter: createMaxLengthFormatter(8),
})
However I want to be able to do something akin to this:
const someFourDigitNumberInput = createFormField({
...otherParams,
valueFormatter: combineFormatters(numberFormatter, createMaxLengthFormatter(4)),
});
Any suggestions how to implement combineFormatters in an elegant ESNEXT way?
.reduceto iterate and use the value of the previous computation as the input for the next. I guess I'll share my own answer but see if something more elegant pops up