Archive for the ‘JavaScript’ Category
All that’s great about CoffeeScript in 40 characters
Today, I needed a JavaScript equivalent of Ruby’s Array#compact
(which returns the array stripped of any nil
values).
A standard JavaScript implementation looks like this:
Array.prototype.compact = function() { var x, _i, _len, _results; _results = []; for (_i = 0, _len = this.length; _i < _len; _i++) { x = this[_i]; if (x != null) { _results.push(x); } } return _results; };
But since I’m using CoffeeScript, I get this monstrosity of line-noise and distraction for free when I type this:
Array::compact = -> x for x in @ when x?
This is some of the best of CoffeeScript: array comprehensions, implicit return
, the existential operator ?
, and more. Taking 11 lines of JavaScript busywork and turning it into 40 pithy, elegant characters.
Spindlytext: write in the sky with the Google Earth API
I’ve just released Spindlytext on Github. It’s the library that powers the live data display in Pigeon Sim, by creating KML linestrings in the shape of letters.
Overlapping markers on your Google Map? Meet OverlappingMarkerSpiderfier
Ever noticed how, in Google Earth, marker pins that overlap each other spring apart gracefully when you click them, so you can pick the one you meant?
And ever noticed how, when using the Google Maps API, the exact same thing doesn’t happen?
This code makes Google Maps API version 3 map markers behave in that Google Earth way. Small numbers of markers (up to 8, configurable) spiderfy into a circle. Larger numbers fan out into a (more space-efficient) spiral.
Cubic splines in JavaScript (via CoffeeScript)
For a recent study two colleagues needed to elicit a cumulative probability distribution function (CDF) from survey respondents.
We decided it would be nice to allow respondents to interact with this CDF after providing some key values, and implemented this in the web browser with <canvas>
(falling back on FlashCanvas for IE).
In the process, we implemented three kinds of cubic spline calculation in the ever-wonderful CoffeeScript: natural, clamped and (what we actually needed) monotonic cubic splines.
You can play with some examples below: click-and-drag the round handles, or double-click to enter values directly. Feel free to borrow the code (ideally with attribution) if it’s of use to you.
Extended and properly-multi-line Regular Expressions for JavaScript
Perl, Ruby, and some other languages support a readable ‘extended’ regular expression syntax, in which literal whitespace is ignored and comments (starting with #) are available. They also support a multi-line mode where the . character matches anything, including a newline.
JavaScript does neither of these: it doesn’t recognise the extended syntax, and its version of multi-line only allows the ^ and $ characters to match the beginnings and ends of lines within a string (it will never allow the . to match a newline).
So I wrote the following function to convert extended and fully-multi-line RegExp source strings to the basic syntax that JavaScript understands.
Signing Amazon Product Advertising API calls in Ruby
I have a simple site that generates covers for CDs I burn from iTunes purchases and so on (it pre-dates widespread use of JS libraries, and is in much need of prettifying). The site uses Amazon Product Advertising API calls to search and retrieve album cover art and track listings. Since earlier this month, such API calls have to be cryptographically signed.
This is somewhat annoying — the site’s original design has it communicating independently with Amazon (using Amazon’s XSLT API feature to transform their XML data into JSON), and that’s no longer possible with the use of a private key. But it’s not unfixable. The site now sends its API call first to my server, which returns a signed version, and then forwards the signed call on to Amazon.
I found most of what I needed for this on Chris Roos’ blog, but his version still wasn’t quite working for me (the two problems I recall are that Ruby’s CGI.escape doesn’t quite follow Amazon’s requirements, and that times need converting to GMT).
Getting a Firefox extension’s directory from within the extension
When creating a Firefox extension recently, I was surprised how much pain is involved simply in finding out, from within an extension, where that extension’s files are installed.
You have to create a ‘component’, which entails a fair chunk of unintelligible boilerplate code (well, unintelligible unless you’re much better acquainted with Firefox’s innards than developing a basic extension generally requires you to be).
Plenty of places will tell you roughly how to do it. But, after some experimentation, let me show you exactly how.
- Copy this JavaScript file into your extension’s /components directory (if that directory doesn’t exist yet, create it).
- Add these lines to your
chrome.manifest
:
component {723079F5-F880-40BB-8283-8266DEA93960} components/getExtDir.js contract @mackerron.com/getExtDir;1 {723079F5-F880-40BB-8283-8266DEA93960}
- Use it from elsewhere in your extension like so:
var own_path = Components.classes["@mackerron.com/getExtDir;1"] .createInstance().wrappedJSObject.getExtDir(); |
Update, August 2011 — Firefox 3 made this a bit less hairy, and Firefox 4 introduced a small but incompatible change. The updated code above works in Firefox 3 – 6, and most likely beyond. However, to make knowing your own directory useful (e.g. in order to locate and run an AppleScript there) you may have also to set <em:unpack>true</em:unpack>
in install.rdf
. This activates the old extension unpacking behaviour, which is deprecated because it increases load time.