Created
August 15, 2015 09:48
-
-
Save nvurgaft/a3c2d77a68edc56d7df2 to your computer and use it in GitHub Desktop.
Examples for using anonymouse functions with functional programming in Javascript
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
<div> | |
<p id="text1"></p> | |
<p id="text2"></p> | |
</div> |
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
function forEach(array, fn) { | |
var result = []; | |
for (var i=0; i<array.length; i++) { | |
result.push(fn(array[i])); | |
} | |
return result; | |
} | |
var data = ['hello', 'ms', 'robinson']; | |
var iteratedData = forEach(data, function(item) { | |
return item.length; | |
}) | |
document.getElementById('text1').innerHTML = iteratedData; | |
function filter(array, fn) { | |
var result = []; | |
for (var i=0; i<array.length; i++) { | |
if (fn(array[i])) { | |
result.push(array[i]); | |
} | |
} | |
return result; | |
} | |
var datum = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
var newData = filter(datum, function(item) { | |
if (item%3===0) { | |
return true; | |
} | |
}); | |
document.getElementById('text2').innerHTML = newData; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment