DEV Community

Cover image for javascript combine few functions into pipeline
Itayp1
Itayp1

Posted on • Updated on

javascript combine few functions into pipeline

combine few functions into pipeline

sometimes we need to pass our data in some pipe line that will produce the updated data

and its can be accomplished in many ways

the simplesd way is that

const obj = { name: "itay", age: 28, isValid: null }

const upperCase = (({ name, ...other }) => ({ ...other, name: name.toUpperCase() }))
const setAge = (({ age, ...other }) => ({ ...other, age: (new Date().getFullYear() - age) }))
const validName = (({ isValid, name, ...other }) => ({ ...other, name, isValid: name.match(/^[A-Za-z]+$/) ? true : false }))
const func1res = upperCase(obj)
const func2res = setAge(func1res)
const func3res = validName(func2res)
console.log(func3res)

yes its working
but its not the best way

we can combine all the funtions into one line like that

console.log(validName(setAge(upperCase(obj))))

but its will become harder to maintain in that way
there is another option
slightly different

reducers

reducer is an method that belong to array object
and its can help us to combine those funtions

i assume that you already know that is an reducer
and if not i will show a little example that sum the number in the array

var numbers = [1, 2, 3, 4];
const sum2Numbers = (accumulator, currentNum) => currentNum + accumulator


console.log(numbers.reduce(sum2Numbers, 0))

this is how we combine the functions with reducer

const compose = (arr, val) => arr.reduce((updatedObj, currentFunc) => currentFunc(updatedObj), val)


2

its will get the same result
{ age: 1992, name: 'ITAY', isValid: true }

to explain this i will use a difrent example
we have 2 function 2415

const doubleit = (a) => a * a
const addit = (a) => a + a

we want a way to combine thoes funcs with minimum effort
lets begin

first we create function that run on every function and every time get the last calculated value

const combineFumc = (value, currentFunc) => currentFunc(value)
// like the sum2Numbers , in runtime its will be something like
(value, currentFunc) => currentFunc(value)
(2, doubleit ) => doubleit (2)

then we create the compose function

const coompose = (functionList) => (val) => functionList.reduce(combineFumc, val)

the first value will be an array

const additTwiceAndDoubleif = coompose([addit, addit, doubleit, doubleit])

so you can decide how do you want to combine your function

and then you just pass to the function the value to calculate

 console.log(additTwiceAndDoubleif(2))

Top comments (0)