Last active
September 12, 2019 17:06
-
-
Save revanth0212/659b5abe90c76d4c35044486365bf42b to your computer and use it in GitHub Desktop.
Custom implementation of Ramda's Compose Function without any dependencies. This function has been implemented with tail recursion, so no more stack overflow issues.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Compose function | |
*/ | |
function _compose(functions, param) { | |
const lastFunction = functions.pop(); | |
const result = lastFunction.call(null, param); | |
return functions.length === 0 ? result : _compose(functions, result); | |
} | |
function compose(...functions) { | |
const lastFunction = functions.pop(); | |
return function(...initalParams) { | |
const result = lastFunction.apply(null, initalParams); | |
return functions.length === 0 ? result : _compose(functions, result); | |
}; | |
} | |
module.exports = { compose } | |
/** | |
* Sample functions | |
*/ | |
function getAge({ age }) { | |
return age; | |
} | |
function head(arr) { | |
return arr[0]; | |
} | |
function filterUser(userName) { | |
return function(users) { | |
return users.filter(({ name }) => userName === name); | |
}; | |
} | |
/** | |
* Data | |
*/ | |
const users = [ | |
{ | |
name: "Jed", | |
age: 25 | |
}, | |
{ | |
name: "Revanth", | |
age: 25 | |
} | |
]; | |
/** | |
* Example | |
*/ | |
compose( | |
console.log, | |
getAge, | |
head, | |
filterUser("Jed") | |
)(users); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment