Learning JavaScript the right way™, part 2

Click here for part 1

JavaScript only has two types of data structures, called Objects and Arrays. Neither is really what the name implies. Many other languages – Java comes to mind – come loaded with a whole list of trees, lists, maps, etc. JavaScript manages to cover all use cases with only two, at the cost of efficiency. They’re both always passed by reference.

Arrays

They should be used to store sets of identical elements. They can contain any type of elements and even mix types inside of the same array, but don’t mix types because it defeats the entire points of arrays. “Real arrays”, as in C, are contiguous blocks of memory. JavaScript “Arrays” aren’t really arrays, instead they’re a specializtion of the JavaScript Object type (more on that in part 3) and they work like lists. JavaScript provides a handy built-in literal notation using square brackets.

var arr1 = [1,2,3,4,5]; //Declares an array with 5 elements
console.log(arr1[0]); //Outputs 1
console.log(arr1.length); //Ouputs 5

Continue reading

A more functional split function

The split function is a major part of modern languages and string processing. It transforms a string (or an array or a list) into a list of sub-elements by splitting on every occurrence of the supplied separator. The best thing about split is that it fits right into modern programming paradigms: a split string can be mapped over and then joined, folded, filtered, etc.

Strictly speaking, split is a looping operation, but unlike a for/while loop, a map or a fold, split operates at a higher abstraction level. It’s an implicit loop. It’s about the WHAT, not the HOW. It’s about the result, not the process. There’s room for improvement, though. It can be made more generic and much more powerful.
Continue reading

Coffeescript: for key, value in array

I just found something really disappointing with Coffeescript.


obj = {a:1, b:2, c:3}
arr = [3,4,5]

# Prints: 3-0, 4-1, 5-2
for v,k in arr
    console.log v+"-"+k

# Prints: 1-a, 2-b, 3-c
for k,v of obj
    console.log v+"-"+k

Notice how I had to invert the key and value in the array loop? It’s annoying. It’s inconsistent. It’s amateurish.

I understand that 98% of the time, for … in is used without the need for a key reference, but sometimes you need to keep track of the loop counter and the coffeescript.org documentation is really not helpful in that regard.

I could make my own loop counter, but it’s even uglier than memorizing this gotcha, so I’m going to stick with the gotcha..

My impressions after a week of CoffeeScript

Until a few days ago, I was a hardcore pure JavaScript believer.
I didn’t want to hear anything about Dart, TypeScript, LiveScript, CoffeeScript, IcedCoffeeScript and all the other compile-to-JS languages out there. To me, they were only an additional layer of stuff that could go wrong. I still think they’re all too focused on solving a non-issue with JS, namely the prototypal Object system. I absolutely love the approach used by Javascript when it comes to OOP because it takes the best functional-style features of JS and creates an elegant way of managing objects during runtime.

I’ve been following the development of ECMAScript 6 for many months, and I’m excited by all the new features, like list comprehensions, splats, array destructuring, syntactic sugar for map/reduce/filter/etc and many others. I’m sure you can see where I’m going with this. I knew CoffeeScript provided all that, but to me it was just a layer of features that are about to land in V8 any second now, so why bother learning it? Well, for one, the dense syntax is great. It can be really confusing at first. Take this snippet, for example. It prints the numbers from 1 to 5, waiting 1 second every time.

for (var i=1;i<=5;i++){
    (function(i){
        setTimeout(function(){
            console.log(i);
        }, i*1000);
    })(i);
}

Continue reading

Learning JavaScript the right way™, part 1

I’ve been thinking about writing this for a while and I’ve finally decided to bite the bullet. This is going to be very dense and terse, I’ll go deep into details whenever I feel necessary. This whole series is all about avoiding the bad parts of JavaScript and focusing on the good ones. There isn’t any lack of explanations online about how a for loop works, so I’m assuming that the reader already knows:

  • The structures of imperative programming (for, while, if, else, return, etc.)
  • The principles of Object Oriented Programming (class, instance, interface, method, etc.)
  • Simple data structures (arrays, lists, hashmaps)
  • Big-O notation on a basic level (O(1) vs O(n), etc)

The style recommendations (do’s and don’ts) are my own opinion of what makes JS code readable and maintainable.

Parts:

  1. Basic types
  2. Arrays
  3. Objects
  4. Functions and Scope
  5. Prototypes
  6. Good JS practices


Continue reading

My new favorite sort algorithm

I haven’t laughed that much in a while.

I just learned about 4chan’s brilliant Sleep Sort algorithm (2011): start a thread for each integer in the array and make it sleep X seconds where X is the value of the integer. When the thread resumes, add that integer to the end of the sorted array. Time complexity is left as an exercise for the reader.

My asynchronous JS implementation:


Array.prototype.sleepsort = function(callback){
    var self = this,
        sorted = [];
    for (var i=0,len=self.length;i<len;i++){
        (function(i){
            setTimeout(function(){
                sorted.push(self[i]);
                if (sorted.length === self.length){
                    callback(sorted);
                }
            }, self[i]);
        })(i);
    }
};

[85, 91, 25, 72, 37, 27, 24, 42, 38, 18].sleepsort(function(arr){
    console.log(arr); // [18, 24, 25, 27, 37, 38, 42, 72, 85, 91]
});

The original bash version:


#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait

Original 4chan thread
Code golf on Stack Overflow
Mandatory XKCD reference