javascript / expert
Snippet
Declarative Functional Pipelines for State Transitions
Functional pipelines allow you to compose state updates as a series of pure transformations. This makes complex logic easier to test and reason about by breaking it into small, single-responsibility functions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const pipe = (...fns) => (val) => fns.reduce((acc, fn) => fn(acc), val);const addMetadata = (s) => ({ ...s, updatedAt: Date.now() });const validate = (s) => (s.value < 0 ? { ...s, error: true } : s);const handleUpdate = (newValue) => {const pipeline = pipe((s) => ({ ...s, value: newValue }),validate,addMetadata);setState(pipeline(state));};
react
Breakdown
1
const pipe = (...fns) => (val) => fns.reduce((acc, fn) => fn(acc), val);
A higher-order function that chains multiple functions together from left to right.
2
validate,
A pure function that checks the state integrity and returns a new state object.
3
setState(pipeline(state));
Executes the entire chain of logic and applies the final result to the component state.