thingsinjars

  • 8 Aug 2010

    The quest for Extreme JavaScript Minification

    As described in detail previously, I've recently taken part in the JS1K competition where you have to squeeze something cool and clever into 1024 bytes of JavaScript. The quest to condense has become quite addictive and I found myself obsessing over every byte. This is the kind of stuff that the Closure Compiler does quite well automatically but there are some cases where you just need to get in there and manually tweak.

    Here are some of the tricks I've picked up in my struggle for extreme minification:

    Basic improvements

    Use short variable names.

    This one's fairly obvious. A more useful addition to this is:

    Shorten long variable names.

    If you're going to be accessing an element more than once, especially if it's a built-in element like 'document', you'll save a few bytes every time you reference it if you create a shortened reference to it.

      document.body.style.overflow="hidden"
      document.body.style.background="red"
      (74 characters)
    

    can shorten to

      d=document;b=d.body;s=b.style;
      s.overflow="hidden";
      s.background="red"
      (69 characters)
    

    and any references to s after are going to save 19 characters every time.

    Remove whitespace

    This one's so obvious, I don't need to mention it.

    Set Interval

    The extremely handy setInterval function can take either a function or a string. If you give it an anonymous function declaration:

      setInterval(function(){x++;y--},10);
    

    You will use up more characters than if you give it just the inside of the function as a string:

      setInterval('x++;y--',10);
    

    But the outcome will be the same.

    Little-used aspects

    Not many people use JavScript's scientific notation unless they're doing scientific stuff but it can be a great byte saver. The number 100 is equivalent to 1 * 10^2 which is represented in JavaScript as 1E2. That's not a great saving for 100 but 1000 is 1E3, 10000 is 1E4. Every time you go up a factor of 10, you save 1 byte.

    Fight your good style tendencies

    In the war against space, you have to bite the bullet and accept that you may need to sacrifice some of your hard-earned practices. But only this once. Don't get in to the habit, okay?

    No zeroes

      0.5  = .5
    

    Yeah, it looks ugly but it works and saves a byte.

    Naked clauses

      if {
        :
        :
      } else y
    

    The y looks so naked out there. No braces to keep it warm. But if you only have one statement in your else clause, you don't need them...

    No semi-final. . . final-semi. . . Semi-colon. No final colon.

    You don't need a semi-colon on your last line, even if it does make it look as though you've stunted its growth.

    The final few bytes

    Operator precedence

    You don't need brackets. Brackets are handy for you as the programmer to remember what's going on when and to reduce ambiguity but if you plan correctly, most of the time you won't need brackets to get your arithmetic to work out.

      b.getMilliseconds()/(a*250) 
          is the same as
      b.getMilliseconds()/a/250 
    

    Shorthand notation

      l=l+1;l=l%14;
      l++;l%=14;
      l=++l%14;
    

    The three lines above are equivalent and in order of bytes saved.

    Shorthand CSS

    If you need to set some CSS values in your script, remember to pick the most appropriate short form. Instead of s.background='black', use s.background='#000' but instead of s.background='#F00', use s.background='red'. In the same vein, the statements margin="0px" and margin=0 mean the same but the latter saves bytes.

    Don't be generic

    One final thing to mention is that these little challenges are not the norm. If you find yourself trying to squeeze code down like this you're probably working on a very specific project. Use that to your advantage and see if there are any savings to be made by discarding your usual policies on code reuse. In the JS1K challenge, we're provided with a specific HTML page and an empty script tag. One good saving made here (and mentioned in my previous post) was the way I grabbed the reference to the canvas element. The standard method is to use the id assigned to the canvas.

      d.getElementById('c')
    

    Which is a good generic solution. No matter what else was on the page, no matter what order stuff was in, this would return the canvas. However, we have a very specific case here and the canvas is always going to be in the same place - the first child of the body element. That means we can do this instead:

      b.children[0]
    

    This makes use of the reference we grabbed to the body earlier. If the page were rearranged, this would stop working but as it won't, we've saved 8 bytes.

    In conclusion

    Yes, this is all quite silly but it's also fun and tricky. Attempting these kinds of challenges keep us developers mindful of what it is we actually do and that makes it an extremely productive silly hobby.

    Development, Javascript, Geek, Guides

  • 4 Aug 2010

    Elementally, my dear JavaScript

    The Angry Robot Zombie Factory launched its second iPhone/iPad app this week. I haven't mentioned it much yet because I spotted a minor typo in the final version after it had been approved so I submitted an update immediately. To get an early copy (like those misprinted stamps where the plane is upside down), go check out The Elementals. It's free, too. It's a simple, cartoonish periodic table.

    Yesterday, the 1k JavaScript demo contest (#js1k) caught my eye. The idea is to create something cool using 1024bytes of JavaScript or less. I rootled around in the middle of The Elementals, grabbed the drawing function and 20 minutes later had made my entry.

    The code I submitted is quite minified but isn't obfuscated. When it's unfolded, you can follow the flow fairly easily.

    var d = document,
    b = d.body,
    s = b.style,
    w = innerWidth,
    h = innerHeight,
    v = b.children[0],
    p = 2 * Math.PI,
    Z = 3,
    x = tx = w / 2,
    y = ty = h / 2;
    

    The above is a bunch of declarations. Using things like d = document and b = d.body allows reuse later on without having to resort to the full document.body.style and saves a bunch of characters. When you've got such a small amount of space to play with, every character counts (mind you, the ZX81 only had 1k of RAM and look what you could do with that). Now that I'm looking at it, I think I could have tidied this a bit more. Darn. The sneaky bit about this code is the way we grab the reference to the canvas. The code d.getElementById('c') uses 21 characters but if we look at the provided HTML, we can use the fact that the canvas is the first child of the body element. The code b.children[0] uses 13 characters instead.

    s.margin = "0px";
    s.background = "black";
    s.overflow = "hidden";
    v.width = w;
    v.height = h;
    t = v.getContext("2d");
    

    This sets the provided canvas to be the full width and height of the window then grabs the drawing context of it so we can make pretty pictures.

    zi = function () {
     Z++;
     Z %= 14
    };
    m = function (X) {
     return (X * 200) % 255
    };
    

    Functions to be reused later. zi increases the number of spinning circles and is used by onmousedown and ontouchstart (oh yes, it works on the iPad, too). m is a mapping of the index of the circle to a colour. The 200 is arbitrary. I played about a bit until I found some colour combinations I liked.

     d.ontouchstart = function (e) {
     zi();
     tx = e.touches[0].pageX;
     ty = e.touches[0].pageY
    };
    d.onmousemove = function (e) {
     tx = e.clientX;
     ty = e.clientY
    };
    d.onmousedown = zi;
    

    Setting the event handlers.

    function r() {
     t.globalCompositeOperation = 'lighter';
    

    I played about with the various composite operations. Lighter seemed the nicest.

     t.clearRect(0, 0, w, h);
     t.save();
     x = x + (tx - x) / 20;
     y = y + (ty - y) / 20;
     t.translate(x, y);
    

    Originally, the circles followed the mouse pointer exactly but it lacked any life. By adding in this bit where the movement is delayed as if pulling against friction, it suddenly became a lot more fun and dynamic.

     var c = new Date();
     for (var i = 1; i <= Z; i++) {
      t.fillStyle = 'rgba(' + m(i) * (i % 3) + ', ' + m(i) * ((i + 1) % 3) + ',' + m(i) * ((i + 2) % 3) + ', 0.5)';
      t.beginPath();
      t.rotate((c.getSeconds() + i) / (i / 4) + (c.getMilliseconds()) / ((i / 4) * 1000));
      t.translate(i, 0);
      t.arc(-10 - (Z / 5), -10 - +(Z / 5), 100 - (Z * 3), 0, p, false);
      t.fill()
     }
    

    Erm. Yeah. In essence, all this does is figure out where to draw the circles, how big and what colour. It looks worse than it is. Line-by-line, it translates to:

    1. Find out the current time
    2. For each circle we want to draw,
    3. Pick a colour based on the index of the circle
    4. Start drawing
    5. Turn by some amount based on the time and the index
    6. Move by a small amount based on the index
    7. Actually draw, making the circles smaller if there are more of them.
    8. Fill in the circle with the colour.
    9. Right curly bracket.
     t.save();
     t.fillStyle = "white";
     for (var i = 1; i <= Z; i++) {
      t.beginPath();
      t.rotate(2);
      t.translate(0, 28.5);
      t.arc(-120, -120, 5, 0, p, false);
      t.fill()
     }
     t.restore();
     t.restore()
    }
    

    This does pretty much the same as the one above but always the same size and always the same colour. The t.save and t.restore operations throughout mean we can add the transformations onto each other and move stuff relative to other stuff without messing up everything. Goshdarn, that was technical.

    setInterval(r, 10);
    

    Kick it all off.

    That make sense? Good. Now go make your own js1k entry and submit it. Then download The Elementals. Or Harmonious.

    Geek, Javascript, Development

  • 21 Dec 2009

    Crowdsourced Weather - Part 2

    So, I couldn't help myself. I had a niggling idea at the back of my head that I needed to get out. After coming up with this Twitter weather idea last week, I decided to spend a couple of hours this weekend building it. As if I didn't have other things I should have been doing instead...

    It works pretty much exactly how the pseudocode I mentioned last time describes. Every few minutes, a script will search Twitter for mentions of any weather words from several different languages. It will then look up the location of the person who tweeted that and store it. Single reports might be wrong and users might not have stored their actual location but over a large enough sample, this system becomes more accurate. The script removes any matching twets older than 6 hours.

    To display, I actually ended up using Geohashes instead of Geotudes because it is easier to simplify them when you zoom out just by cutting off the tail of the hash. For example, the physical area denoted by gcvwr3qvmh8vn (the geohash for Edinburgh) is contained within gcvwr3 which is itself contained within gcv. There are a few technical problems with geohashes but it seems the best fit for this purpose. If anyone knows of any better suggestion, please let me know. I do realise that this is quite possibly the slowest, most inefficient JavaScript I've ever written because it makes an AJAX call for every graticule and it probably should just send the South-East and North-West bounds and get back an array of them but, like I said, there were other things I should have been doing. Because the overlaid grid changes resolution based on zoom level, there are a few places where it is either tragically slow (resolution too fine) or terribly inaccurate (resolution too rough). That's just a case of tweaking the algorithm. Similarly, it's set to display reports of weather if there are 2 or more matches but it could be tweaked to only show if a larger number have reported something.

    So go, play with the Twitter-generated weather map. If someone can come up with a good, catchy name, or some better graphics, that'd be great, thanks.

    Source code is available: twitter-weather-1.0.zip [Zip - 298KB].

    You'll need your own Twitter login and database account to use it.

    Geek, Development, Javascript, CSS, Design

  • 17 Dec 2009

    Crowdsourced Weather

    This is a more general version of the #uksnow map idea. It's a crowd-sourced weather map which relies on the fact that any one individual tweet about the weather might be inaccurate but given a large enough sample, enough people will mention the weather in their area to make this a workable idea. It doesn't require people to tweet in a particular format.

    To get info

    Have an array of weather words in various languages (rain, hail, snow, schnee, ame, yuki)
    every 5 minutes:
    	foreach weatherword
    		search twitter for that word
    			http://search.twitter.com/search.atom?q=rain
    		retrieve latest 100 tweets
    		foreach
    			get user info
    				http://twitter.com/users/show.xml?screen_name=username
    			get user.location if available
    			geocode
    			save:
    				username, time, lat, long, geotude, weatherword
    		Remove any tweets about this weatherword older than 6 hours.
    			
    

    To display info

    Show a Google map
    Based on current Zoom level, split the current map into about 100 geotudes
    foreach geotude
    	search database for any weather results for that block (probably using an ilike "1234%" on the geotude field)
    	sort by weatherword count descending
    	draw an icon on top of that block to show the most common weatherword
    	
    If the user zooms in, recalculate geotudes and repeat.
    

    I quite like that this uses geotudes which I think are an excellent idea.

    I built a very basic version of this. Read more about it in Part 2.

    Ideas, Development, Javascript, CSS, Design

  • newer posts
  • older posts

Categories

Toys, Guides, Opinion, Geek, Non-geek, Development, Design, CSS, JS, Open-source Ideas, Cartoons, Photos

Shop

Colourful clothes for colourful kids

I'm currently reading

Projects

  • Awsm Street – Kid's clothing
  • Stickture
  • Explanating
  • Open Source Snacks
  • My life in sans-serif
  • My life in monospace
Simon Madine (thingsinjars)

@thingsinjars.com

Hi, I’m Simon Madine and I make music, write books and code.

I’m the Engineering Lead for komment.

© 2025 Simon Madine