Efficient rounding in JavaScript

So you have some number, x, which you want to round to the nearest integer. Easy, right?

x = Math.round(x);

Sure, but is this the fastest option? I think not.

x = x < 0 ? x - 0.5 >> 0 : x + 0.5 >> 0;

What the heck's going on here? >> is JavaScript's right shift operator. It shifts a number's binary representation n bits to the right, where n is the value to the right of the operator. Since n is 0 in this case, no shifting will occur, although the resulting value will be an integer.

Note that this approach results in -82.5 being rounded to -83.

If, for some reason, your code calls Math.round() millions of times, it may be worth investigating the bitwise approach to avoid the overhead of all those function calls.

Stick to Math.round() the rest of the time, though, as it makes for much clearer code. Never optimize prematurely.

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

DigitalColor Meter

DigitalColor Meter

I thought this recent post on the Minimal Mac blog well worth sharing:

When was the last time you checked out your Utilities folder? Well, if your answer was “What’s that?” then let me explain. Inside of your Applications folder is another folder called Utilities that is filled with all sorts of wondrous things that most people either don’t know or completely forget are there. Even veteran Mac users are guilty of this. I know I am.

DigitalColor Meter is one example of this. The other day, I wanted to find out the web safe color of a particular item on the screen of my Mac for a web design project I was working on. My first step was to go searching the Internet for such a tool (preferably free). Then, in the midst of said search, I was reminded that this little tool was not only already on my Mac, did exactly what I wanted, but also did it better than any of the tools I was able to find.

The point is that, even the tools we think we know can always reveal a little something we don’t. The Mac is an incredibly deep and rich OS and there are few that know it all. I’m going to spend some time every day for the next little while spending some time getting to know some more of these built in tools I largely have ignored and see if I have any practical applications for using them. You will likely see more posts like this in the coming days.

Reblogged by ¡ɜɿoɾɪɹℲ with this extremely nifty addition:

To take your Digital Color Metering to the next level, you can drag the color off of the well on the right (next to the R G B labels) into any standard color picker to bring it over. Sometimes, you can even drop it straight into an object in another app!

Give it a try: sample a color, press cmd-shift-h to hold it, then drag and drop from the swatch an object in Pages or Keynote.

I'm going to find this incredibly useful. No more grabbing a portion of the screen, switching to Photoshop, creating a new document, hitting ⌘V, switching to the eyedropper tool, double-clicking the foreground colour swatch to invoke the Color Picker, and then clicking on the appropriate pixel to find its colour value.

I don't think I'll miss this process, somehow, although my flatmate'll miss the camera shutter sound that accompanies screen captures on OS X (he really likes it, for some reason).

Man after my own heart

From Wikipedia on Mies van der Rohe's Seagram Building:

[An] interesting feature of the Seagram Building is the window blinds. As was common with International Style architects, Mies wanted the building to have a uniform appearance. One aspect of a façade which Mies disliked, was the disordered irregularity when window blinds are drawn. Inevitably, people using different windows will draw blinds to different heights, making the building appear disorganized. To reduce this disproportionate appearance, Mies specified window blinds which only operated in three positions – fully open, halfway open/closed, or fully closed.

This, taken from Werner Blaser's Mies van der Rohe, is also brilliant:

The plan of the brick villa is a good example of the way in which Mies van der Rohe developed the art of structure from the very beginning. The structure of a brick wall begins with the smallest unit into which the whole can be divided: the brick. The dimensions are calculated in terms of the basic unit of the brick.

Want more?

Check out the archives.