Last active
December 13, 2015 23:39
-
-
Save zkat/4993214 to your computer and use it in GitHub Desktop.
wondering about this coffeescript thing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Some quick hand-translations of code found in http://coffeescript.org/ | |
| * I know they're trying to show off random features, but going through these | |
| * makes me wonder how much convenience CS actually adds. | |
| */ | |
| // # Assignment: | |
| // number = 42 | |
| // opposite = true | |
| var number = 42; | |
| var opposite = true; | |
| // # Conditions: | |
| // number = -42 if opposite | |
| if (opposite) number = -42; | |
| // # Functions: | |
| // square = (x) -> x * x | |
| var square = function(x) x*x; // Yes, this is legal. | |
| // # Arrays: | |
| // list = [1, 2, 3, 4, 5] | |
| var list = [1, 2, 3, 4, 5]; | |
| // # Objects: | |
| // math = | |
| // root: Math.sqrt | |
| // square: square | |
| // cube: (x) -> x * square x | |
| var math = { | |
| root: Math.sqrt, | |
| square: square, | |
| cube: function(x) x * square(x) | |
| }; | |
| // # Splats: | |
| // race = (winner, runners...) -> | |
| // print winner, runners | |
| // Splats are nice, but they don't save *that* much work... | |
| var race = function(winner) { | |
| var runners = [].slice.call(arguments, 1); | |
| // or with lodash/underscore: | |
| // var runners = _.tail(arguments); | |
| console.log(winner, runners); | |
| }; | |
| // # Existence: | |
| // alert "I knew it!" if elvis? | |
| if (elvis) alert("I knew it!"); | |
| // # Array comprehensions: | |
| // cubes = (math.cube num for num in list) | |
| var cubes = [math.cube(num) for (num of list)]; // JS 1.7 | |
| var cubes2 = list.map(math.cube); // Even better | |
| // Functions | |
| // fill = (container, liquid = "coffee") -> | |
| // "Filling the #{container} with #{liquid}..." | |
| function fill(container, liquid) { | |
| liquid = liquid || "coffee"; | |
| return "Filling the "+container+" with "+liquid+"..."; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment