So you’re using CoffeeScript, great! But are you exploiting all its features? Functional CoffeeScript is fun, but you need some helpers. In this tutorial we’ll cover the most essential functional helpers and techniques to build a solid foundation for your next project. Let’s keep it DRY!
Snippets #1
I’ll start my blog by posting a couple of useful helpers. The first one lets you count the items of an array that may have duplicates:
0 1 2 3 4 5 6 7 8 9 10 |
function count(xs) { return xs.reduce(function(a,e) { return a[e] = ++a[e]||1, a; },{}); } var data = ['one','one','two',3,4,4,4,'five']; count(data); //=> {one: 2, two: 1, 3: 1, 4: 3, five: 1} |
This second snippet lets you format a string similar to printf
:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
function format(str, arr) { return str.replace(/%(\d+)/g, function(_,m) { return arr[--m]; }); } var text = 'Hello %1. Are you %2 today?'; var values = ['Mike','busy']; var result = format(text, values); console.log(result); //=> "Hello Mike. Are you busy today?" |