Skip to content

Instantly share code, notes, and snippets.

@rsrini7
Created April 8, 2014 08:52
Show Gist options
  • Select an option

  • Save rsrini7/10102666 to your computer and use it in GitHub Desktop.

Select an option

Save rsrini7/10102666 to your computer and use it in GitHub Desktop.
Javascript - Higher Order Function
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
// Define two simple functions
var add_2 = function(x) {
return x + 2;
};
var double = function(x) {
return 2 * x;
};
var sqrt = function(x){
return x * x;
}
// map is cool function that accepts 2 arguments:
// func the function to call
// list a array of values to call func on
var map = function(func, list) {
var output=[]; // output list
for(idx in list) {
output.push( func(list[idx]) );
}
return output;
}
var buildProcessor = function(func) {
var process_func = function(list) {
return map(func, list);
}
return process_func;
}
// calling buildProcessor returns a functoin which is called with a list input
// using buildProcessor we could generate the add_2 and double list processors as follows:
process_add_2 = buildProcessor(add_2);
process_double = buildProcessor(double);
// => [7, 8, 9]
//process_double([5,6,7]) // => [10, 12, 14]
document.body.innerHTML = buildProcessor(sqrt)([5,6,7]);
//-->
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment