Created
July 29, 2015 06:16
-
-
Save dnasca/0ec70248f86f82e5a71a to your computer and use it in GitHub Desktop.
Pattern: Iteration and Applying - applying a callback function to multiple[each] item in a list
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
| // create a function called forEach that iterates over all items in a list and calls a callback for each item | |
| // note: this concept is attached to the array object automatically. this is just to illustrate what is happening under the hood | |
| items = ['one', 'two', 'three']; | |
| //iterator function 1 | |
| forEach = function (array, func) { //func = callback function that is passed in (the iterator!) | |
| for (var i = 0; i < array.length; i++) { | |
| func(array[i], i); //item in array, and index item in array | |
| } | |
| }; | |
| forEach(items, function (item, idx) { //print each index and each item | |
| console.log(idx = ': ' + item); | |
| }); //output: 0: one, 1: two, 2: three | |
| // iterator function 2 (map function) - transform items | |
| map = func (array, func) { | |
| var newArray = []; | |
| var result; | |
| for (var i = 0; i < array.length; i++) { | |
| result = func(array[i], i); | |
| newArray.push(result;) | |
| } | |
| return newArray; | |
| }; | |
| newArray = map(items, function(item, idx) { | |
| return item + '-new'; | |
| }); | |
| //inspect newArray object //array: ["one-new","two-new","three-new"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment