Sunday, July 21, 2013

How to make a sandwich in Javascript

Michelle, if you're reading this, start getting ready for our open mic duet. Don't even worry about the set list, I'll take full responsibility for picking the songs I like. Here's some that you might want to learn how to sing:

by Wings:
Let me roll it
Band on the run

by Blue Oyster Cult:
Burning for you
Take me away
Astronomy

by Led Zeppelin:
That's the way
D'yer M'ker
Houses of the Holy

by Dusty Springfield:
Son of a preacher man

by Save Ferris:
Come on Eileen (their cover rocks, you play the power chords, I'll practice the crazy ska rhythm)

by Squeeze:
Tempted

by Bogushevskaya:
Cafe Ekipazh

Let me know which ones you don't absolutely love so I can convince you otherwise. Everyone else go listen to these and imagine how well they'd sound if they sounded slightly worse. Pretty fantastic? Agree.

One and a half more days of freedom and then my favorite girl will be back to torture me. I need to think about what kind of things I can do now that I can't when she's around. Other than tell vicious lies on this blog with impunity, or sleep with other women. I guess I should get all my bad singing, bad drawing, and bad dancing out of the way so she doesn't have to do too much criticizing right after a hard week's rocking in Korea.

And now, a cool trick from today's JavaScript camp. I've used this before, but never in the general form:

function partial(fn) {
var args = [].slice.call(arguments, 1);
return function() {
return fn.apply(null, args.concat(arguments));
};
}

What this allows you to do is precreate functions when you know some arguments ahead of time. So for example, if you have a sandwich function:

function sandwich(bottom, top, middle) {
return {
bottom: bottom,
middle: middle,
top:top
}
}

...and you know a "good" sandwich always has a pancake on the bottom and a pop-tart on top, you can make yourself a shortcut function easily:

var goodSandwich = partial(sandwich, 'pancake', 'pop-tart');

This essentially hardcodes the (bottom, top) set of parameters and gives you back a function that expects only one parameter - 'middle'. So now you can use the goodSandwich function to make sandwiches with different contents but the same shell:

// equivalent to sandwich('pancake', 'pop-tart', 'turkey')
var goodTurkeySandwich = goodSandwich('turkey');

// equivalent to sandwich('pancake', 'pop-tart', 'Mark')
var goodMarkSandwich = goodSandwich('Mark');

// equivalent to sandwich('pancake', 'pop-tart', 'cheeseburger')
var goodCheeseburgerSandwich = goodSandwich('cheeseburger');

// equivalent to sandwich('pancake', 'pop-tart', sandwich('pancake', 'pop-tart', 'cheeseburger'))
var doubleDecker = goodSandwich(goodSandwich('cheeseburger'));

Mm, a cheeseburger wrapped in two pancakes and two pop-tarts. That'll get you bulimic in no time.

No comments: