passThrough
passThrough
(value: any, fnArray: function[]) => Result
Pass a value through
fnArray
.Each function takes the result of the prior function as its parameter.
const increment = n => n + 1 const double = n => n * 2 const toAnswer = n => 'answer: ' + n passThrough(1, [increment, double, toAnswer]) // is 'answer: 4' passThrough('a', []) // is 'a'
const increment = (n: number) => n + 1 const double = (n: number) => n * 2 const toAnswer = (n: number) => 'answer: ' + n passThrough(1, [increment, double, toAnswer]) // is 'answer: 4' passThrough('a', []) // is 'a'
const increment = n => n + 1 const double = n => n * 2 const toAnswer = n => 'answer: ' + n passThrough(1, [increment, double, toAnswer]) // is 'answer: 4' passThrough('a', []) // is 'a'
const increment = (n: number) => n + 1 const double = (n: number) => n * 2 const toAnswer = (n: number) => 'answer: ' + n passThrough(1, [increment, double, toAnswer]) // is 'answer: 4' passThrough('a', []) // is 'a'
Just like compose, passThrough gives us a flexible and readable way to combine logic. It's one of the big reasons I find functional programming to be helpful.
Sometimes we want to pass a value through some functions to get a result. Below, we have the five-day weather forecast and want to calculate the average low. Let's pass the forecast through some functions to do this.
const forecast = [ { high: 68, low: 54 }, { high: 62, low: 50 }, { high: 63, low: 52 }, { high: 55, low: 43 }, { high: 58, low: 49 }, ] const avgLow = passThrough(forecast, [ mapValues(get('low')), getAverageValue, roundToNearest('0.1'), ]) console.log(avgLow) // is 49.6
type Forecast = { high: number low: number } const forecast: Forecast[] = [ { high: 68, low: 54 }, { high: 62, low: 50 }, { high: 63, low: 52 }, { high: 55, low: 43 }, { high: 58, low: 49 }, ] const getLow = get('low')<Forecast> const avgLow = passThrough(forecast, [ mapValues(getLow)<Forecast[]>, getAverageValue, roundToNearest('0.1'), ]) console.log(avgLow) // is 49.6
const forecast = [ { high: 68, low: 54 }, { high: 62, low: 50 }, { high: 63, low: 52 }, { high: 55, low: 43 }, { high: 58, low: 49 }, ] const avgLow = passThrough(forecast, [ mapValues(get('low')), getAverageValue, roundToNearest('0.1'), ]) console.log(avgLow) // is 49.6
type Forecast = { high: number low: number } const forecast: Forecast[] = [ { high: 68, low: 54 }, { high: 62, low: 50 }, { high: 63, low: 52 }, { high: 55, low: 43 }, { high: 58, low: 49 }, ] const getLow = get('low')<Forecast> const avgLow = passThrough(forecast, [ mapValues(getLow)<Forecast[]>, getAverageValue, roundToNearest('0.1'), ]) console.log(avgLow) // is 49.6
When to use passThrough vs. compose?
They can often be used interchangeably. Compose allows you to name a group of functions, which can sometimes be helpful. Other times a name is unnecessary, and you just want to pass data through.