Things in Jars

Simon Madine (thingsinjars)

@thingsinjarsFollow me on Twitter

Hi, I’m Simon Madine and I make digital toys and write guides on web development.

I'm a senior web dev and evangelist for Nokia Maps in Berlin.

  • Twitter
  • Flickr
  • GitHub
  • Forrst
  • Shelvist
  • Last.FM
  • RSS
  • Simple and clever beats clever

    Written 3 Dec 2011

    Guides,Geek,Javascript

    When messing about with another little game idea, I found myself retyping (for the umpteenth time) the same little bit of value bounding code I use a lot:

    var x = Math.max(0, Math.min(y, 1))
    Which basically translates to:
    "Set x to be the value of y as long as it's between 0 and 1. 
    If not, set it to 
      0 if it's smaller or 
      1 if it's larger."

    Of course, 0 and 1 don't need to be the boundaries, I'm just using them for convenience.

    Instead of continuing with the game, I decided to take a little tangent and see if there was any way I could rewrite this so that the syntax was a bit more obvious. I'd like to be able to use syntax like:

    x = [0 < y < 1]

    to mean the same. Written exactly as above, JS will try and evaluate left-to-right, changing the comparisons to booleans. The statement would become

    y = 0.5
    
    x = [0 < y < 1]
    x = [0 < 0.5 < 1]
    x = [true < 1]
    x = [false]

    Similarly:

    y = -0.5
    
    x = [0 < y < 1]
    x = [0 < -0.5 < 1]
    x = [false < 1]
    x = [true]

    My first thought was to be clever about it, I wanted to try and figure out how to partially evaluate the expression and take the different outcomes to figure out the logic required. If '0 < y' was false, then y is less than zero therefore outside our bounds, the return value should then be 0. If the first part is true and the second is false then we know the value is higher than our bounds....etc and so on.

    This proved to be a logical dead-end as there was no good way to partially evaluate the statements. Not without preparsing the JS, anyway. Which leads me onto the second attempt...

    Preparsing the JS

    The next attack on the problem was the idea of reading the JS as a string, shuffling it around quickly and silently (not like a ninja, more like a speedy librarian in slippers) and put it back where it was.

    So I began to look at ways to recreate that. I remembered from many, many years ago (two, actually) Alex Sexton creating the genius abomination that is goto.js and how that used some kind of preparsing. A quick skim through the code later and I ended up on James Padolsey's site looking at parseScripts.js.

    In the end, all I needed to do was include parseScripts (which is a generalised form of the code I ended up using for the whitehat SEO question from last month) and provide a new parser function and script type.

    parseScripts(/:bound/, function(unparsed) {
     return unparsed.replace(/\[(\d)\s*<\s*(\w)\s*<\s*(\d)\]/g, "Math.max($1, Math.min($2, $3))");
    })

    I'm not saying parseScript isn't clever because it most definitely is but I am saying it's simple. There's not always a need to branch off into deep technical investigations of partial evaluation when a simple search-and-replace does the job better and faster.

    For someone always going on about bringing simplicity and pragmatism into development, you'd think I'd have gotten there faster...

    Bounded Range

    The final bounded range syntax code is available here (hint: view the console). It's silly but it was a fun half-hour.

    Improvements?

    Do you know of any better way to do this? Is there a clever parsing trick we can use instead? Is there, indeed, any language which has this syntax?

    Comments

  • Whiteboard Laptop Lid

    Written 26 Nov 2011

    Design,Geek

    I use whiteboards a lot. Whether I'm coding, explaining some concept or other, sharing the results of a meeting, wherever. If there's a whiteboard nearby, I'm quite likely to jump up and start drawing big diagrams with lots of arrows and wavy lines. When there's not a whiteboard, I still jump up but I tend to lean more towards big handy gestures drawing diagrams in the air (I recently watched a video of myself presenting with the sound turned down and I looked like an overenthusiastic mime artist dancing to 'Vogue').

    To make sure I always have a whiteboard to hand, I roped in Jenni to help with a little home craft-making.

    D.I.Y. Laptop-lid Whiteboard

    Blue Peter style list of things:

    You'll need scissors and/or a craft-knife, double-sided sticky tape, a measuring tape, a bit of sturdy white cardboard or a thing sheet of opaque PVC and some sticky-backed clear plastic. You'll also need a laptop and an grown-up to help you with the cutting.

    • Scissors and plastic

    First, measure the top of your laptop and figure out how big your whiteboard can be and draw that on your cardboard or plastic (from now on referred to as 'white board').

    • Measure twice...

    Next, cut your cardboard or plastic to the right size. Remember to measure twice and cut three times or something like that. I can't remember exactly but there some ratio of measuring to cutting. Do that.

    • ...cut three times

    If you're using a piece of shiny PVC or something like that, you can miss this next bit. If you're using cardboard or something else, you'll need to cover it with the transparent sticky-backed plastic.

    • Sticky-backed plastic

    The final preparation stage is to put the double-sided sticky tape on the back and position it on your laptop lid.

    • Double-sided sticky tape

    Try not to take any photos one-handed while doing this step or this may happen:

    • Oops.

    There you go. A portable, take-anywhere whiteboard in 10 minutes. Apart from needing a pen, of course, and a cloth to wipe it so you don't end up with smudges all over your laptop bag, we're done.

    • Stuck.
    • Not completely opaque.
    • Action shot!

    I can now take my whiteboard with me everywhere I go for a meeting. Long may the diagramming continue.

    Comments

  • Poor man's touch interface

    Written 17 Nov 2011

    Javascript,Geek,Guides

    Here's a little code snippet for today.

    While I was making the 3D CSS Mario Kart, I needed a simple, drop-in bit of code to handle touch interfaces. I looked through some old experiments and found a rough version of the code below. It was based on this KeyboardController by Stack Overflow user Bob Ince.

    It doesn't do anything clever. All it does is provide a simple way to attach functionality to touch events in different areas of the screen – top-left, top-center, top-right, middle-left, middle-center, middle-right, bottom-left, bottom-center, bottom-right. My apologies to any Brits for the spelling of centre as 'center'. It's the Internet, we have to.

    How to use

    Include this code:

    
    function TouchController(areas, repeat) {
      var touchtimer;
      document.onmousedown = document.ontouchstart = document.ontouchmove = function(e) {
        var position;
        e.preventDefault();
        e.touches = [{'clientX':e.pageX,'clientY':e.pageY}];
        switch(true) {
        case (e.touches[0].clientY<window.innerHeight/3) : 
            position = 'top';
            break;
        case (e.touches[0].clientY>(2*window.innerHeight)/3) : 
            position = 'bottom';
            break;
        default : 
            position = 'middle';
            break;
        }
        position+='-';
        switch(true) {
        case (e.touches[0].clientX<window.innerWidth/3) : 
            position += 'left';
            break;
        case (e.touches[0].clientX>(2*window.innerWidth)/3) : 
            position += 'right';
            break;
        default : 
            position += 'center';
            break;  
        }
    
        if (!(position in areas)) {
          return true;
        }
    
        areas[position]();
        if (repeat!==0) {
          clearInterval(touchtimer);
          touchtimer= setInterval(areas[position], repeat);
        }
        return false;
      };
      // Cancel timeout
      document.onmouseup = document.ontouchend= function(e) {
      clearInterval(touchtimer);
      };
    };
    

    Now, all you need to do to attach a function to a touch event in the top-left area of the screen is:

    TouchController({
      'top-left': function() { topLeftFunction();}
    }, 20);
    

    I use this for direction control in the Mario Kart experiment which maps exactly onto the cursor keys used for the normal control.

    TouchController({
      'top-left': function() {  // UP + LEFT
    				drawMap.move({y: 2}); 
    				drawMap.move({z: drawMap.z + 2}); 
    				drawMap.sprite(-1) 
    			  },
      'top-center': function() {  // UP
    				drawMap.move({y: 2}); 
    			  },
      'top-right': function() {  // UP + RIGHT
    				drawMap.move({y: 2}); 
    				drawMap.move({z: drawMap.z - 2}); 
    				drawMap.sprite(1) 
    			  },
    
      'middle-left': function() {  // LEFT
    				drawMap.move({z: drawMap.z + 2}); 
    				drawMap.sprite(-1) 
    			  },
      'middle-right': function() {  // RIGHT
    				drawMap.move({z: drawMap.z - 2});
    				drawMap.sprite(1) 
    			  },
    
      'bottom-left': function() {  // DOWN + LEFT
    				drawMap.move({y:  - 2}); 
    				drawMap.move({z: drawMap.z + 2}); 
    				drawMap.sprite(-1)  
    			  },
      'bottom-center': function() { 
    				drawMap.move({y:  - 2}); 
    			  },
      'bottom-right': function() {  // DOWN + RIGHT
    				drawMap.move({y:  - 2}); 
    				drawMap.move({z: drawMap.z - 2}); 
    				drawMap.sprite(1)  
    			  },
    }, 20);
    

    If you need anything clever or you need two or more touches, you should use something else. This is just a simple drop-in for when you're copy-paste coding and want to include touch-screen support.

    Comments

  • Super Mario Kart CSS

    Written 14 Nov 2011

    Geek,CSS,Toys

    Silly CSS Fun for a Sunday Afternoon

    Yesterday, I decided to mess around with 3D CSS transforms. I've used them here and there for various things (the flip animations in Shelvi.st, for example) but nothing silly.

    My mind wandered back to an early HTML5 canvas demo I saw ages ago where Jacob Seidelin had written Super Mario Kart in JS and I wondered if it would be possible to do the pixel-pushing part of that demo in CSS.

    An hour later and we have this:

    Super Mario Kart CSS

    Yes, it's silly. Yes, it's nothing like playing Mario Kart and, no, there isn't any acceleration. That wasn't the point, however. View the source to see the description of the rotations and transforms.

    Comments

  • newer posts
  • older posts

Browse articles by category:

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

Recent side-projects

  • Insta-Art
  • 8-Bit Alpha
  • Shelvi.st
  • The Elementals
  • Harmonious

Toys

Find my digital toys at thelab.thingsinjars.com.

Contact

Send me a message via Twitter.

Adopt-a-Museum

@thingsinjars:

    © 2012 Simon Madine