Showing posts with label foreach. Show all posts
Showing posts with label foreach. Show all posts

Monday, February 24, 2014

SnowBlower and Object Composition


I'm going to talk about this "library" and why it's very useful. It takes a lot of the compositional techniques of objects and makes it really fun.

Here's an example of how to use SnowBlower.


It takes all the functions and objects that you pass to it, and either executes it in the context of your new object, or mixes it into your new object. If you need polyfills for your environment, just define Array.prototype.reduce, Object.create, and replace the Object.prototype.hasOwnProperty function to reflect your environment.

It's designed to be small and SnowBlower assumes you have all the pieces and closures that define your object up front. If you need to compose factories, you can just create a function that does it for you.


This is a DRY method of reusing functions you have already defined to compose objects. The sky is the limit! Just thought I would share this compositional technique with you.

~function(){console.log('josh')}();

Friday, November 15, 2013

Array forEach Synergy

Today I wanted to share another nice and small use case for the forEach loop for the intermediate/beginner javascript developer.



As a disclaimer, my code isn't perfect, it can be optimized, and my goal isn't give you snippets of code to steal. However, I do this to show you how to make your own javascript functions yourself. Take my code and tweak it, add some useful functions that may help you finish your project.

I hope my samples help grow and motivate you to strive and become a better programmer.

In functional health,
-Josh

Friday, November 8, 2013

Defining Plugin Architecture for Constructor Libraries

Even in a hypothetical world where objects are packaged into black boxes it would seem that convention and configuration butt heads repeatedly until developers are quite frustrated with their code. In the real world it's even more difficult to package up black boxes because the language architecture design is fundamentally flawed. (I'm looking at you Javascript global namespaces!)

So, I've personally set out to develop quick easy ways to make boxes that appear to be black boxes, but are highly configurable.

Here were some of the goals I had in mind for designing my personal plugin Architecture.

  1. Had to be easy!
  2. Had to be quick!
  3. Plugin Convention over configuration
  4. Boilerplate-able
  5. Should give access to constructor options to determine where the construction of the object goes
  6. Should provide a local scope for hidden variables relative to each object.

Here's a boilerplate you can use to create something like I'm describing.

I've a feeling we're not in the global namespace anymore.

If some of that code looks confusing to you, I suggest looking at the concept of functional expressions. They give you a "pseudo-blackbox" that can see the global namespace.

If you are good on closures, then we move on to the next step. Actually defining the code to make plugins work. Here's what I personally use:

This code is rather simplistic, but lets take a look a bit deeper to see the real beauty of it.

This little function right here is where ALL the magic happens. Let me show you an example of why this is "magic." Writing a plugin is very easy to do here.

Boom! Now you can call this:

As if that wasn't enough... let's go back and look at another example. A full on event emitter API.

Take some serious time to learn what just happened here. Each one of the functions created in that script are local to the object itself, because the plugin constructor code is called only once. This allows you to enclose private variables into a black box namespace. It's completely abstracted away to the developer behind the curtain.

Please pay no attention to the variables behind the functional expression.

In functional health,
-Josh

Tuesday, November 5, 2013

Native vs Functional Loops

Native loops...

...are a functional portion of the javascript language and allow you to repeat functionality of code for a certain number of times specified by the conditions of the loop.

These examples are fairly easy and trivial. If you are not proficient in javascript loops, I highly recommend learning how to construct one from scratch here.

Functional loops provide a different mechanism for looping over the items in an array. They also have much larger implications for memory management and coding techniques.

Example: a user wants to loop over items in an array and perform a static operation.

This example is obviously bad, because the same result could be achieved by calling target = array.slice();, but look a little bit closer at the example below.

Boom. Now you can enclose objects with functions and local variables.

So now that we have our toolset, let's make a few rules on when certain loops are needed.

Native loops

  • When a functional context is not needed
  • Concatenating strings
  • Looping through strings
  • Anywhere that performance matters greatly

To put it simply, if the code requires speed and performance, chances are a for loop may be indicated. Especially for simple operations.

Lastly, the indications for functional loops...

Functional loops

  • When a closure is needed(I.E. Variables need to be obscured)
  • Chaining Maps (see example below)
  • When the calling function needs to be called multiple times in other places in the code (using a named function)
  • When Performance probably doesn't matter (and trust me, javascript is pretty fast)
  • When file size DOES matter

The code looks more fun, and is more expressive. It's less terse, but that's the price you pay for a functional language expression

In functional health

-Josh

Thursday, September 5, 2013

Replacing the jQuery.each function

http://api.jquery.com/jQuery.each/

Compare the following examples:

Example 1 (Using jQuery):

   $("section").each(function(index, element){
       //do something with element
   });

Or even better
   $.each($("section"), function(index, element){
       //do something with element
   });

Example 2 (Native javascript):

   var elements = document.querySelectorAll("section");
   for(var i=0;i<elements.length; i++){
      var element = elements[i];
   }

Note that these pieces of code do the exact same thing.  They loop through all the elements in an array.  In fact the first solution looks very elegant.  Some might even argue it's the functional way a javascript developer should code.

Nobody, however, should argue which one gets better performance when run in browser.

Honestly, anyone can read the examples, but who really benefits from code like Example 1?  It's not the page viewer, because the client had to download a 45kb library to get "foreach" functionality that makes the page run slower.  It's also not the developer, because the developer missed out on making their code faster. I guess the answer is that nobody truly benefits except for beginners, who get shortchanged unknowingly.

There is however one more suggestion:

 [].forEach.call( nodeListReference, function (node) {
  // now do whatever you want to do with node
});

Feel free to comment below. All opinions are valid and welcome.