Thursday, December 26, 2013

jshint is good, but...

Let's just be upfront here because I don't want to hurt peoples feelings on jshint (which is apparently known for hurting people's feelings.) I can say many things about jshint , and 99% of them are good. In fact, there are a LOT of good practices that jshint enforces that I think are absolutely invaluable. Yet, here I am really just annoyed with a bunch of these "Code errors." Let me give you some examples.

1. I'm a NodeJS developer working on a test suite, using SHOULD and MOCHA, and I use jshint to test and make sure I use good coding practices. Here's what happens:


Well SCREW YOU TOO. Look at all these unmeaningful errors. I mean, require is definitely defined. I shouldn't have to deal with the jshint output like this.

2. I'm working on a token reader for the front end.



What happened here? I expected an assignment and a falsy check to occur during a while loop, and I got this lame output. Sure it's scrutiny and you can easily rewrite it to something like this:


The question is "Why?". So some novice developer can come in and see what your code does faster? Chances are this small obscurity will teach the novice developer about javascript and the things you can do with it. Sure it's "cute" and silly, but is it really worth your time to change your coding style like this? Just document it.


See, that wasn't so hard. I'd rather teach the beginner the "rules" and then break them.

The following example kills me every time:


Expected a 'break' statement before 'default'.

What if I wanted it to bleed over into the cases and use spaghetti code? Apparently novice coders are too dumb to spend time and figure it out for themselves. Chances are if your code is more complicated, you wanted another statement anyway. Yet, what if the offending sample is simple? What if the code happens to be easier to write and read with the switch statement? That's a matter of your opinion and really the decision should be left up to you.

(It also told me console was not defined but that's arbitrary.)

Look, just make a decision for yourself and use jshint to let it find your bugs before you do. Just make sure you read the error and make a determination for yourself if it's worth "fixing."

I probably spend more time sifting through 'console' is not defined more often than I would personally like to.

~function(){console.log("Josh");}();

Friday, December 20, 2013

Slightly Advanced SQL Aggregation

I hold myself as a programmer first, and a blogger second: so I hope you don't mind if I post a bit on a few SQL techniques I used this week.

Here's today's example:
I need a table of information containing a list of clients with their ID that shows counts by order type: 1,2,3, and OTHER.

Sounds like you should just do multiple select statements for each client right?



WRONG. This query is very hard to maintain and does at least 4 table scans per client. Yuck.

Try this instead:



Look at that maintainable easy to read code (unless you didn't know you could put a case statement inside of an aggregate function.) Now step up your ante, find the latest Order_Date split out by types using the mentioned technique using the Max function.

(hint, here's the answer:)



Sure, this is nothing special, but to someone who wants to increase the size of their Developer Toolbox, don't forget about speed and efficiency.

Have fun,
~Josh

Monday, December 9, 2013

Prudent Object Inheritence (that isn't classical)

Don't even think about classes. I'm really just tired of them, and you should be too. Forever we have been chained to classical inheritance (which I admit is faster for compiled languages.) Yet, maybe it's time we broke free from our bonds of definition and un-define ourselves in a meaningful way.

Hello Inheritance


It is prudent that we remember that our world is not defined. No matter how much science we throw at it, no matter how much the book of definitions grows, there will always be unknown. Our code will never be able to match the vastness of our comprehension and definitions. Clearly there is never a way to get around the fact that computers live in a supremely deterministic world. For this reason, every program should be known as art.

The very first definition of art when googling [Definition of Art]:

"the expression or application of human creative skill and imagination, typically in a visual form such as painting or sculpture, producing works to be appreciated primarily for their beauty or emotional power."

We should remember that we actually make a living off of the fact that programmers take something defined and absolute to create something amorphous and functional. Programmers also take requirements and turn them into something displayed on a screen. This alone is remarkable. In the context of art, we are untypical, yet we try to produce works to be appreciated by their physical or tangible power, rather than their beauty or emotional power. (Or maybe you do?)

The Chains of Determinism and Convention over Configuration




Given the example, I show you inheritance that actually makes sense. When you inherit a simple interface in C#, things become more generic and happy. Do not confuse this for complicated inheritance chains that convolute your code. Applying an interface to multiple objects makes your code flow better and work with different definitions faster. These specific kinds of contracts are exactly what you need.

It also bodes us well to remember that javascript ascends beyond this need to define. It takes all the deterministic work out of your code. What you are stuck with are the conventions you use to define your work, and the configurations you provide to your client.

Why not instead of classes, think of your javascript code like you would a composer? The composer cares not about determinism. In fact, some composers would say their work leads them to the solution. The composer applies musical conventions and not configurations to define their pieces. In fact, most configurations are left up to the conductor who interprets the pieces created by the composer.

Even if you can define the notes used to compose a piece, it makes sense that those notes would mean something so much more!

What does this mean for you?


You are not a composer, (or maybe you are,) and thus, should act accordingly. Instead of relying on supreme indeterminism, rely on some convention in your code. Convention will make your code faster and smaller. Of course, definitely do type checking, but be willing to be flexible where you do it. Wherever your API interfaces with a developer, be flexible enough to call Object.prototype.toString.call(object) and really see what is going on. You may be accepting the input of another library (hopefully with the right conventions) but in complete honesty, you never know what you are going to get.

So throw in the towel, right?

HECK NO.


You should instead, play into javascript like you mean it.

Have the courage to do something like this:



Yeah. I totally went there.

The only adjustment you need to work with javascript is your attitude towards it. Javascript cannot be deterministic. So embrace it's functions and super generic objects, and enjoy your smaller (and somehow faster) code base.

You won't regret it.

Lastly, here is a sample of the stuff you can do with a very small (2kb minified) library that I wrote by hand.



This is the way object coding should be (minus the pyramid syntax that plagues the gist's version of callback hell.)

You define repeatable closures and mixin objects. Suddenly, you have a repeatable way to generate objects. Just don't forget that those pieces can be called directly like this:



Want to actually use it in your project? The command is simple (for node anyway:)



In functional health,
~function Josh(){}()

Friday, December 6, 2013

Classical Inheritance is dead and what you can do about it

There is nothing new in this blog post, but all of this is worth mentioning to everyone repeatedly. If javascript was meant to have classes, it would have had them in the first place. Instead we are stuck with the following clunky syntax and keywords to do type checking.



Instead you probably just wanted this.



Look at how simple that is! It's so much faster. Even to a beginner programmer, the hint that this.name may actually be the name property of the object literal.

Need to do instanceOf? Why not do something like this instead?



Seriously! There's so much less code. In fact, why not just  forget the whole "new" paradigm? Well, maybe not forget, but use it wisely. It also begs the question, how do you make objects repeatedly? Don't you need some kind of overhead? What about applying prototypes to already created objects? Or worse. What about multiple linear inheritance?

Your goal when making applications is get the banana. Not the gorilla, not the jungle, and not everything else. See the following video.

Perhaps it might be overstated that using stampit is quite useful. It is also very close at getting the banana. At 10kb I found that stampit was the correct solution on the back end where we control  the modules. Size doesn't matter on the back end. On the front end, it might be more like a fruit salad to a mobile phone. I also have nothing but respect for Eric's library, because it really showcases the fundamental units of object creation.

Could you perhaps have wanted something smaller? (Yeah it's a pretty shameless plug.)

After all, passing callbacks should be really terse.

We should always remember the few components that comprise our objects and functions: Properties, values, closures, functions, prototypes, and contexts.

Edit:
Don't forget to check out the npm registry for my library composer.js.

Monday, November 18, 2013

Canvas Clickable Regions - Demystified

Let's face it, canvas stuff is never terse and annoying. Creating buttons on a canvas is even harder. First you have to draw the button, change it's state, and other complicated things.

For instance, if the user pushes the mouse down on one clickable region, and drags it over to ANOTHER clickable region, the "click" event will still fire and (therefore) fire the second region's click event.

So what kinds of things do we actually need to figure this stuff out?

Well, for starters, let's demystify the mouse event positions.



This will give you a way to get the mouse location of any click event. So let's build our clickable region first.



Cache the canvas and draw an image...



..and the only things that are missing are the click events...



and put it all together!



The final product looks a bit like this, because you totally took the code and made it work for your project.. right? Get coding people!

In functional health,
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

Monday, November 11, 2013

Sharing: Self Invoked Object Literals

Some techniques aren't new or novel. They are just fun. This isn't really new, or novel either, but it's quite fun.

In fact, some people would probably criticize that it is essentially the same thing as an Immediately Invoked Functional Expression. There are some key differences here though. Take a look at the following code.

It's starting to look like the module pattern, but it creates an object and ships it via function baz to the variable foo with bar's prototype. Alas, the this keyword shows it's confusing head again, but look closely. "this" is the object literal itself.

Finally I'll leave you with a working example.

Sometimes, the "new" keyword is overrated when making objects anyway.

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

Monday, November 4, 2013

Handlebars Templating?

I have been writing small posts lately, so it's probably best if I just cut to the chase.

Handlebars has been tried and true for templating.
Also, I'm in no way advocating for the use of these samples, but I think they speak for themselves. You don't always need a library because you are making an intranet application, or your users use modern browsers. You can code the language yourself!

And one for objects...

"But Josh! I don't want to edit the prototype!"
Fine! Here you go.

I encourage you to at least understand what is going on in this code before you steal it, and certainly be able to implement it yourself.

Having fun with Function.prototype.call

In javascript, using the .call() method allows you to specify the context of whatever object you pass to it. This allows you to call a string method from an array context, and vice versa.

Check out the following script...

In all honesty, it may not be a good idea to use these methods, because they aren't supported on these objects, but check out what happens!

Go nuts and try out some other methods and post them in the comments to see what you come up with.

Wednesday, October 23, 2013

EMCA Sub Arrays - An Interesting Technique

Dealing with javascript arrays can be a breeze, or it can be bothersome. The array.length property having the ability to change the array is VERY difficult to replicate. You almost cannot make your own typed arrays. At least you can get pretty close. Take the following code snippet I am investigating.

Running this code will make a ZOMBIE array (as I call it.)

(Warning, I am not responsible for unintended "features" your code exhibits.)

function SubArray(length){
   Array.call(this); //"Magic"
   if(typeof length == "number" && length%1==0&&arguments.length==1){
     this.length = length; //Length has to be set manually for some reason.
   }
   else{
     var _len = arguments.length;
     this.length = _len;
     for(var i = 0; i<_len; i++)
        this[i] = arguments[i];
   }
}

SubArray.prototype = [];

var x = new SubArray();

Presto Change-o!

Suddenly you have a strongly typed array, albeit with a few small caveats.

//Evaluate the following
var x = new SubArray();

typeof x; //"object" -- Just like when you declare a new Array....
Object.prototype.toString.call(x); //"[object Object]" -- To be expected
x instanceof Array;//true -- This is the way the Array functionality would be identified

x.push(1); //2
x;//[undefined, 1]
x[2] = "test";

//Drum roll please....
x;//[undefined, 1]

Wait... what? The property wasn't even set! It just disappeared. Or did it? Check console.log(x[2]); . So what really happened is the .length property wasn't set and the array wasn't updated. However, if this particular limitation does not hold you back, it's very easy to work with it because you haven't done ANYTHING to modify a native prototype.

I would probably use this technique for some fun stuff, but what you really wanted was an Array in the first place... so just return an array and add some properties to it instead. It's lame, but it works.

Or you could simply wait for Native Object inheritance in some later version of EMCAscript that is coming down the pipeline.

In functional health, Josh

Tuesday, October 22, 2013

Hello Nodewebkit!

Have you ever wondered what it would be like to package up node modules and run them in a windowed desktop environment using HTML and Javascript?

Well, nows your chance!

Node Webkit

Node-Webkit is by far one of the coolest runtime environments ever synthesized by man. Ever. It's currently in 0.8.0-rc1 and is actively being developed by Roger Wang. Let's take a closer look at some of the concepts that were introduced by this framework.

Here is a presentation to get you up to speed if you have not heard of it yet.

Node as a Desktop Runtime Environment

Node webkit takes the Chrome-web-browser and fuses it to the node runtime environment. (Actually the module, require, and global variables are hoisted into a chrome window, but that's too technical. Let's just get started already!)

Getting Started

If you haven't downloaded node.js yet, you may want to download Version v0.10.17. Follow node's instructions on installing it. Or if you are running linux, have git, and make installed...


git clone https://github.com/joyent/node.git
cd node
./configure
sudo make
sudo make install

After that, install grunt. Open a command terminal and type:


npm install -g grunt-cli

Grunt will help streamline your publishing process. Feel free to check out this tutorial on grunt if you are worried about using grunt. Also, make sure to put sudo before the install command if you are running linux.

Next, create a project folder and open a terminal instance to it.

npm init
(package.json)
{ //follow the instructions on creating the file and edit it yourself afterwards
  "main": "index.html",
  "name": "nw-demo",
  "description": "demo app of node-webkit",
  "version": "0.1.0",
  "keywords": [ "demo", "node-webkit" ],
  "window": {
    "title": "node-webkit demo",
    "icon": "link.png",
    "toolbar": true,
    "frame": false,
    "width": 800,
    "height": 500,
    "position": "mouse",
    "min_width": 400,
    "min_height": 200,
    "max_width": 800,
    "max_height": 600
  },
  "devDependencies":{
    "grunt-node-webkit-builder":"~0.1.11"
    //Feel free to add coffeescript and your favorite libraries here
  },
  "js-flags": "--harmony_proxies --harmony_collections",
  "webkit": {
    "plugin": true
  }
}

It will spit out a package.json file for you. This package configures your node-webkit application.

From that folder run...

npm install

...create an index.html file...

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>Hello Node-Webkit!</h1>
</body>
</html>

...and a gruntfile... (gruntfile.js)

module.exports=function(grunt){
    grunt.initConfig({
      nodewebkit: {
        options: {
            build_dir: './webkitbuilds', // Where the build version of my node-webkit app is saved
            mac: true, // We want to build it for mac
            win: true, // We want to build it for win
            linux32: false, // We don't need linux32
            linux64: false // We don't need linux64
        },
        src: ['./*','./js/*','./css/*'] // Your node-wekit app
      }
    });
    grunt.loadNpmTasks('grunt-node-webkit-builder');
    grunt.registerTask('default',['nodewebkit']);
}

... and finally run grunt.

grunt

Whew! That was a lot.

While everything finishes up, (and downloads all the binaries needed to make this happen) we will discuss what you have just created. Essentially, nodewebkit packages up all of your source files into a virtual directory/zip file and delivers them like normal html pages from a web server... (oops, I mean your desktop.)

Once everything is built, look in the \webkitbuilds\releases\{appname} - {timestamp}\win\{appname} folder to find your exe waiting.

Feel free to use require('node-module') right in the window. In fact, node-webkit has it's own native UI library, and the Window object is an instance of node's EventEmitter object. Which means you can listen to native window events by using Window.on().

Conclusion: Get developing already!

In functional health, Josh

Monday, October 21, 2013

Partial Functions and Currying

Functions should be fun.

In fact, functions should be the reason you love javascript. Applying the knowledge of using functions as objects should be on the top of your to-do list. Of course, sometimes it benefits us to write reusable or partial functions for later use.

Take the following code example.

function partialSum(a, b){
 if(b)
   return a+b;
 return function(b){
    return a+b;
 }
}

In the case of partialSum(2), it returns a function. You don't even need to know what b is until it gets called again.

Calling partialSum(2)(3) returns 5.

This approach is limited however. How about taking it a step further?

function Partial(func, bound){
   //Convert the arguments to an array
   var args = [].slice.call(arguments, 2);
   //Return a function
   return function(){
       //function.apply takes a object and an array
    var localArgs = args.slice();
    [].push.apply(localArgs, arguments)
       return func.apply(bound, localArgs);
    //apply all arguments supplied at this 
    //point to func, call it, and return it's value
   }
}

This function returns a partial definition of the supplied function func. Seems complicated, until you realize exactly what it's doing. It's just concatenating a list of arguments and passing it to the supplied function. This approach is still limited by the number of times you can call it however.

Wouldn't it be nice to create a function that could accept any number of calls until enough parameters have been supplied to it? Ask, and ye shall receive:

//Function, Arity, BoundTo
function Curry(func, length, bound){
 //Declare initial stuff
    var args = slice.call(arguments, 3), len = length||func.length;
 //The "Magic"
    function curriedFunction(func, bound, args){
        if(len <= args.length) //then the function is ready to be called...
            return func.apply(bound,args);//pass the arguments to the function
        return function(){ //otherwise pass back a function
            var localArgs = args.slice(); //local copy...   
            push.apply(localArgs, arguments); //Concatenate arguments
            return curriedFunction(func, bound, localArgs); //and call itself
        };
    }
    return curriedFunction(func,bound,args);
}

Take a moment to really read what is going on in this function. It actually knows when to return a partial function. Function.length does a good job of determining the amount of arguments required to complete the function. This function has LOADS of practical applications.

function sum(a,b){
 return a+b;
}
var add2 = Curry(sum)(2);
console.log(add2(4));
//6
console.log(add2(6));
//8
var add10 = Curry(sum)(10);

function template(jsonObject, templateString){
 //do something here
}

var cachedJSONtemplate = Curry(template, 2, {}, JSONGetWrapper());

var result = cachedJSONtemplate("template string here...");
var result2 = cachedJSONtemplate("template2 string here...");

As you can see, the potential is great. Highly configurable code that makes reusability easy (and encouraging) is the great work of the javascript language in action!

In functional health, Josh.

Friday, September 6, 2013

Cleaver - Markdown to HTML Presentations 'a la Node

Go ahead and take a look, it's quite the library.

(Github: jdan/Cleaver) (NPM: cleaver)

To get started run this: npm install -g cleaver

Definitely go check out the documentation on how to use this library, it's a real catch.

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.