Posts tagged "programming"

Decorators in JavaScript

A decorator is a function which takes a function and returns a function:

decorator = (fn) -> fn

Obviously, this doesn't do anything useful. It's the fact that a decorator can return a function which behaves similarly to the function passed to it that makes the pattern interesting. Commonly a decorator will simply wrap a function invocation in a check of some sort:

var loginRequired = function (fn) {
  return function () {
    if (!user.authenticated) {
      return window.location.replace('/login');
    }
    fn.apply(null, [].slice.apply(arguments));
  };
};

The above decorator could be used to "guard" actions that only authenticated users are permitted to perform:

var changeUsername = loginRequired(function (username) {
  $.ajax({
    type: 'PUT',
    url: '/api/1.0/users/' + user.id,
    data: {username: username}
  })});

var changePassword = loginRequired(function (password) {
  $.ajax({
    type: 'PUT',
    url: '/api/1.0/users/' + user.id,
    data: {password: password}
  })});

var deleteAccount = loginRequired(function () {
  $.ajax({
    type: 'DELETE',
    url: '/api/1.0/users/' + user.id
  })});

The CoffeeScript equivalent is quite a bit clearer:

changeUsername = loginRequired (username) ->
  $.ajax
    type: 'PUT'
    url: "/api/1.0/users/#{user.id}"
    data: {username}

changePassword = loginRequired (password) ->
  $.ajax
    type: 'PUT'
    url: "/api/1.0/users/#{user.id}"
    data: {password}

deleteAccount = loginRequired ->
  $.ajax
    type: 'DELETE'
    url: "/api/1.0/users/#{user.id}"

Decorators are commonly used in Python — which provides special syntax for "decorating" functions — but are rarely seen in JavaScript code. This despite the fact that JavaScript's first-class functions are ideally suited to the task. Perhaps CoffeeScript's lighter-weight function syntax will result in decorators making more frequent appearances in JavaScript code.

Solarized

Earlier this week I discovered Solarized, "a sixteen color palette […] designed for use with terminal and gui applications".

Bundles are available for all the popular editors; I went ahead and cloned the Coda bundle. While the code on my screen immediately looked very nice, a few of Justin's colour choices didn't sit well with me.* I spent an hour or two trying a large number of different combinations until my JavaScript file was harmoniously highlighted.

Solarized code snippet
Solarized code snippet

I wanted an even intensity, but didn't allow myself to deviate from Ethan's prescribed colours. I'm happy with the result: the soft highlighting makes the code easier to understand without being a distraction. Only regular expression literals leap forward, but these tend to occur infrequently.

Coda users may be surprised to see method invocations highlighted. That's one of the minor enhancements I've made to the default mode. If you're interested, have a look at Javascript.mode on Bitbucket.

* Blue escape sequences within red regular expression literals are too striking for my liking!

Repeating strings in JavaScript

Python and Ruby share beautiful syntax for repeating strings; PHP's syntax is characteristically ugly.

Python

'=' * 5

Ruby

'=' * 5

PHP

str_repeat('=', 5)

JavaScript?

True to form, repeating strings in JavaScript is ugly and counterintuitive, but kinda cool.

new Array(5 + 1).join('=')

Simulating nonlocal in Python 2.x

Closure is truly wonderful. JavaScript — despite its plethora of quirks — is now widely appreciated, thanks in large part to its lexical scoping. Python 3 is lexically-scoped, too, as the following code demonstrates.

def cache(saved=None):
    def _(thing=None):
        nonlocal saved
        if thing is not None:
            saved = thing
        return saved
    return _
cache = cache()

If (the rebound) cache is passed no arguments (or None), saved is returned. Otherwise, thing is assigned to saved and returned.

>>> cache(2**3)
8
>>> cache()
8

This works thanks to the nonlocal keyword introduced in Python 3, which enables variables in outer scopes to be rebound. So how would one achieve the same result in earlier versions of Python?

Bitwise NOT operator proves useful in JavaScript

JavaScript is a wonderful language. Its syntax, though, leaves a lot to be desired at times. String pattern matching, for example, is rather ugly.

// ugly option 1
if (text.indexOf('✈') != -1)

// ugly option 2
if (text.indexOf('✈') >= 0)

// ugly option 3
if (text.indexOf('✈') > -1)

It'd be nice to be able to write text.contains('✈'), which is both intuitive and self-documenting. The language does provide a way to make such expressions terser, but it's far from obvious.

// bitwise NOT
if (~text.indexOf('✈'))

Bitwise operators make my head spin, but the Perl programmer in me thinks they're awesome. I don't profess to understand why exactly the bitwise NOT operator does what it does, but I've played with it enough to know how it behaves. It's equivalent to the following function, at least for the values that can be returned by indexOf.

function bitwiseNot(n) {
    return -n - 1;
}

indexOf returns -1, 0, 1, 2, 3, or some other positive integer. When these values are used as operands for the bitwise NOT operator, the results are 0, -1, -2, -3, -4, and so on. Therefore, ~text.indexOf('✈') is equivalent to text.contains('✈') in Boolean contexts.

Converting integers to ordinals

When dealing with dates, it's not uncommon to need to convert an integer into an ordinal number (1st, 2nd, 3rd, etc.). While making improvements to Mango recently I wrote a function to do this, first in Python, later in JavaScript.

Python

def ordinal(n):
    if 10 < n < 14: return u'%sth' % n
    if n % 10 == 1: return u'%sst' % n
    if n % 10 == 2: return u'%snd' % n
    if n % 10 == 3: return u'%srd' % n
    return u'%sth' % n

JavaScript

function ordinal(n) {
    if (10 < n && n < 14) return n + 'th';
    switch (n % 10) {
        case 1: return n + 'st';
        case 2: return n + 'nd';
        case 3: return n + 'rd';
        default: return n + 'th';
    }
}

By special-casing 11, 12, and 13, the function becomes incredibly simple.

I'm pleased to have found a context in which JavaScript's switch statement is almost elegant. The problem, usually, is the need to break to prevent fall-through. When used within a function, though, the return statement is able to perform this role, making the JavaScript code almost as readable as the Python equivalent.

Filtering lists in Python, Ruby, and JavaScript

Recently I listened to Gary Bernhardt comparing Python and Ruby. In the talk Gary states that he finds Ruby code ugly and Python code beautiful. He then goes on to say that the things which reduce Ruby's aesthetic appeal are the very things which allow Ruby to do beautiful things impossible in Python.

Gary provides several examples of equivalent code in Python and Ruby to highlight situations in which one language reads better than the other, such as the following.

Python:

'\n'.join(obj.name
    for obj in (
        repository.retrieve(id)
        for id in ids)
    if obj)

Ruby:

ids.map do |id|
  repository.retrieve(id)
end.compact.map do |obj|
  obj.name
end.join('\n')

The Ruby code (the one beginning with ids.map) reads top to bottom and is easy to follow. The Python code is equally succinct but takes a bit of effort to decipher.

I've been greatly enjoying the act of writing JavaScript lately, so simply for pleasure I worked out the JavaScript equivalent.

My first attempt used the filter array method.

ids.filter(function (id) {
    var obj = repository.retrieve(id);
    return obj && obj.name;
}).join('\n');

filter, though, just removes from an array the items which fail the provided "test". So the code above is on the right track, but fails to produce a list of names.

reduce is the correct method for the job. reduce "reduces" an array to a single value, which could be a string, an object, another array — whatever!

Note the empty array ([]) on line 5 – that's our "accumulator".

ids.reduce(function (ids, id) {
    var obj = repository.retrieve(id);
    if (obj && obj.name) ids.push(obj.name);
    return ids;
}, []).join('\n');

Not bad. It's not as elegant as the Ruby code, but it's not "inside out" the way the Python code is.

Self-caching functions in JavaScript and Python

Earlier I wrote some code which repeatedly calls a function which performs a database query – often the same query. This encouraged me to explore various ways to cache the results of function calls in both Python (to solve my immediate problem) and JavaScript (because I find that language endlessly fascinating).

I played around with Fibonacci, which is a well suited to the task: it can be described in just a couple of lines of code yet benefits enormously from caching due to its recursive nature.

JavaScript Fibonacci without caching

function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 2) + fibonacci(n - 1);
}

Python loops can have else clause?!

I write a lot of Python. I also write a lot of JavaScript. As I switch between the two (often several times in a day) I sometimes find myself trying to do something in one using the syntax of the other. The most common example is joining a list.

Python:

' '.join(['foo', 'bar'])

JavaScript:

['foo', 'bar'].join(' ')

Often — as is the case above — the syntactical differences are minor, but there are times when there's no direct translation.

MooTools, for example, adds the every method to the Array object. This makes it possible to write some rather terse conditional statements.

var numbers = [87, 33, 21, 75];
if (numbers.every(function (n) { return n % 3 == 0; })) {
    window.alert('The numbers are all divisible by 3.');
}

Python lists have no comparable method, so how would one write this in Python?

numbers = [87, 33, 21, 75]
if [n for n in numbers if n % 3 == 0] == numbers:
    print 'The numbers are all divisible by 3.'

This approach involves using a list comprehension to create a list of numbers which are divisible by 3, and comparing this list to numbers. If the lists are equal, everything in numbers is divisible by 3.

Now for something a bit more challenging

Assume that we have a list of documents, and we want to know which of the documents contain all the terms in a list of search terms.

// (MooTools) JavaScript

var terms = ['python', 'list', 'methods'], matches = [];
documents.each(function (document) {
    if (terms.every(function (term) {
        return document.body.indexOf(term) != -1;
    })) matches.append(document);
});

Here, we could use the list comprehension approach as before.

# Python

terms = ['python', 'list', 'methods']
matches = []
for document in documents:
    if [t for t in terms if document.body.find(t) != -1] == terms:
        matches.append(document)

This is reasonably succinct, but not terribly efficient since each document is checked for every search term. Given that we're not interested in documents that lack even a single search term, it should be possible to rewrite this code so that we don't waste time on lost causes.

It turns out that Python has just the thing for the job: in Python, a loop statements may have an else clause!

terms = ['python', 'list', 'methods']
matches = []
for document in documents:
    for term in terms:
        if document.body.find(term) == -1:
            break
    else: # every term was found
        matches.append(document)

From 4. More Control Flow Tools:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

I'm looking forward to finding more good spots to make use of else clauses with my Python loops. :D

First matching item

When writing code one often needs to grab the first item in a collection that has certain characteristics. For example, one may have a list of Student objects and need to fetch the one with a certain id.

The task is trivial: loop through the list and compare each student's id until a match is found or all the students in the list have been inspected, whichever comes first.

In the past, I've tended to take advantage of return statements to exit the loop as soon as a match is found. The examples here are in Python, but the same patterns apply to other languages.

def student_by_id(students, id):
    for student in students:
        if student.id == id:
            return student
    return None

This appoach strikes me as inelegant when the function is called in one place only. Today a different approached occurred to me.

student = None
for student in students:
    if student.id == id:
        break
    student = None

Here, we break out of the loop as soon as a match is found, preserving the student of interest in the variable student. Each time through the loop student is cleared to ensure that student is empty once we've finished looping if there are no matches.

The first line is required to handle empty lists.

I think I'll use this approach from time to time. Let me know if you're aware of another option.