Helper functions for functional style in typescript
This library provides a collection of functional programming primitives and utilities for TypeScript, enabling more expressive and composable code. It includes tools for error handling, data transformation, and functional programming patterns.
The library uses a BaseResponse<T> type that handles both successful results and errors in a functional way:
type BaseResponse<T> = {
data: T;
error: null;
} | {
data: null;
error: SerializableError;
}Result<T>- Constructor for successful resultsError<T>- Constructor for error resultsserializeError- Serializes errors for client-server communicationwithResult/withError- Transform success/error caseswithAsyncResult- Async version of withResult for Promise-based operations
compose- Compose two functionscurry/uncurry- Convert between curried and uncurried functionsID- Identity functioneffect- Create side effects while preserving data flow
map- Curried version of Array.mapreduce- Curried version of Array.reduceflatten- Flatten array of BaseResponse into single BaseResponsepartition- Split array into two based on predicateappend/appendTo- Add elements to arrays
Fst/Snd- Get first/second elements of tupleswithFst/withSnd- Transform first/second elementsbinaryReduct- Create reducers operating on tuple elementsprojection- Work with function operating on tuples
equals- Curried equality checkcontainedBy- Check if element exists in arrayfilterCondition- Conditional filteringchoose- Branch based on predicateinvert- Negate boolean values
Error handling:
const result = await someOperation()
.then(withResult(data => transform(data)))
.then(withError(err => ({ ...err, hint: 'Try again' })));Data transformation:
const numbers = [1,2,3,4];
const [evens, odds] = partition(numbers, n => n % 2 === 0);Function composition:
const addOne = (n: number) => n + 1;
const double = (n: number) => n * 2;
const addOneAndDouble = compose(double, addOne);The library provides several useful type definitions:
Implies<T,U>- Function type from T to UProduct<T,U>- Tuple type [T,U]Predicate<T>- Boolean function on TSerializableError- Error type safe for serializationBaseResponse<T>- Result type handling success/failureDouble<T>- Tuple type [T,T]
Contributions are welcome! Please feel free to submit a Pull Request.