Skip to content

Instantly share code, notes, and snippets.

@josemariagarcia95
Last active November 23, 2018 11:46
Show Gist options
  • Save josemariagarcia95/40bf629cb4de7f7a12fe90b2571752a4 to your computer and use it in GitHub Desktop.
Save josemariagarcia95/40bf629cb4de7f7a12fe90b2571752a4 to your computer and use it in GitHub Desktop.
Example of currifying functions in JavaScript
//The function we're gonna currify
let extractEmotion = function( media, callback ) {
console.log( 'This is extractEmotions' );
callback( media );
};
//The previous function receives a callback
let test = function( media ) {
console.log( 'I\'m the callback and I\'ve received ' + media );
};
extractEmotion( 'Holi', test );
//Output:
//This is extractEmotions
//I'm the callback and I've received Holi
//This function returns a function which called the function passed as an argument (extractEmotions)
//with its parameters, but this time the second argument, the callback, is set to the callback we pass to curryFunction
//as second argument
function curryFunction( func, callback ) {
return function( media ) {
func( media, callback );
};
}
//We reassign the callback to make sure that the output is the expected one
test = function( media ) {
console.log( 'I\'m the callback in curry and I\'ve received ' + media );
};
extractEmotion = curryFunction( extractEmotion, test );
//Now extractEmotion only receives one argument. The callback, which was the second argument, was already set in curryFunction
extractEmotion( 'Holi' );
//Output:
//This is extractEmotions
//I'm the callback in curry and I've received Holi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment