Using IIFE in JavaScript and creating your own Each function


Solving for Each

fi.each(collection, callback)Iterates over a collection of elements, passing each element in turn to a callback function. Each invocation of callback is called with three arguments: (element, index, collection). If collection is a JavaScript object, callback's arguments will be (value, key, collection). Returns the original collection for chaining.
const unmodifiedTestArr = [1, 2, 3, 4]const unmodifiedTestObj = {one: 1, two: 2, three: 3, four: 4}describe('each', function () {const alert = chai.spy();const testArr = [1, 2, 3, 4]const testObj = Object.assign({}, unmodifiedTestObj)const spy = chai.spy(x => true)it('calls alert with each element passed', function () {fi.each(testArr, alert)expect(alert).to.have.been.called.exactly(testArr.length)})it('calls alert properly on object values', function () {fi.each(testObj, spy)const objValues = Object.values(testObj)objValues.forEach((val) => { expect(spy).to.have.been.called.with(val) })})it('returns the original collection', function () {const result = fi.each(testObj, spy)expect(testObj === result).to.equal(true)expect(objectsEqual(testObj, result)).to.equal(true)})})
each, as in forEach, is a function that takes in some data and a callback, which I like to call an action because to me that means doing work, and returns the original data, for chaining.first, we'll need to evaluate what kind of data type we are dealing with here. if its an array, we can slice it and assign to a variable; or even do a spread operator to make a copy. however, if its an object, we are dealing with key value pairs--we want the values. luckily there is a built-in way to do this I've researched, so we don't have to build that test out ourselves, although we could. ultimately, it too returns an array. how very convenient. next, now that our data is sanitized for processing, it is good to go and iterate on. we are going to apply that action to every element, doing the work, whatever it may be. We make use of the index, the copied collection and the callback for the entire length of data.finally, return the original test data unscathed. what are some errors or side-effects though? Will have to test again.
const fi = (function() {  return {
each: function() {
return "Each"

map: function () {
return "Map"

reduce: function(){
return "Reduce"
###example callconsole.log(fi.each())
//=> Hello



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
aaron feingold

aaron feingold

web developer making apps for people with appetite