Created
August 28, 2018 15:41
-
-
Save AndrewThian/99685018249670f55412108bae910574 to your computer and use it in GitHub Desktop.
This file contains 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
// another approach is used by libraries such as jQuery | |
// similar to annoymouns-closure.js but now we passing global variables as parameters | |
var $ = { window: {} }; | |
(function (globalVariable) { | |
// Keep this variables private inside this closure scope | |
var privateFunction = function() { | |
console.log('Shhhh, this is private!'); | |
} | |
// Expose the below methods via the globalVariable interface while | |
// hiding the implementation of the method within the | |
// function() block | |
globalVariable.each = function(collection, iterator) { | |
if (Array.isArray(collection)) { | |
for (var i = 0; i < collection.length; i++) { | |
iterator(collection[i], i, collection); | |
} | |
} else { | |
for (var key in collection) { | |
iterator(collection[key], key, collection); | |
} | |
} | |
}; | |
globalVariable.filter = function(collection, test) { | |
var filtered = []; | |
globalVariable.each(collection, function(item) { | |
if (test(item)) { | |
filtered.push(item); | |
} | |
}); | |
return filtered; | |
}; | |
globalVariable.map = function(collection, iterator) { | |
var mapped = []; | |
globalVariable.each(collection, function(value, key, collection) { | |
mapped.push(iterator(value)); | |
}); | |
return mapped; | |
}; | |
globalVariable.reduce = function(collection, iterator, accumulator) { | |
var startingValueMissing = accumulator === undefined; | |
globalVariable.each(collection, function(item) { | |
if(startingValueMissing) { | |
accumulator = item; | |
startingValueMissing = false; | |
} else { | |
accumulator = iterator(accumulator, item); | |
} | |
}); | |
return accumulator; | |
}; | |
}($)); | |
var items = $.map([1,2,3,4], function (item, index) { | |
return item | |
}) | |
console.log(items) | |
// javascript modules for beginners | |
// https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc | |
// part 2 | |
// https://medium.freecodecamp.org/javascript-modules-part-2-module-bundling-5020383cf306 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment