Skip to content

Commit a7c0c38

Browse files
committed
Merge branch 'master' of github.com:coffeescript-cookbook/coffeescript-cookbook.github.com
2 parents 0184315 + 95c1280 commit a7c0c38

File tree

6 files changed

+275
-6
lines changed

6 files changed

+275
-6
lines changed

authors.textile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ _The following people are totally rad and awesome because they have contributed
1414
* Sebastian Slomski [email protected]_
1515
* Aaron Weinberger [email protected]_
1616
* James C. Holder [email protected]_
17+
* Jason Giedymin [email protected]_
1718
* ...You! What are you waiting for? Check out the <a href="/contributing">contributing</a> section and get cracking!
1819

1920

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
layout: recipe
3+
title: Reducing Arrays
4+
chapter: Arrays
5+
---
6+
7+
h2. Problem
8+
9+
You have an array of objects and want to reduce them to a value, similar to Ruby's <code>reduce()</code> and <code>reduceRight()</code>.
10+
11+
h2. Solution
12+
13+
You can simply use Array's <code>reduce()</code> and <code>reduceRight()</code> methods along with an anonoymous function, keeping the code clean and readable. The reduction may be something simple such as using the <code>+</code> operator with numbers or strings.
14+
15+
{% highlight coffeescript %}
16+
[1,2,3,4].reduce (x,y) -> x + y
17+
# => 10
18+
{% endhighlight %}
19+
20+
{% highlight coffeescript %}
21+
["words", "of", "bunch", "A"].reduceRight (x, y) -> x + " " + y
22+
# => 'A bunch of words'
23+
{% endhighlight %}
24+
25+
Or it may be something more complex such as aggregating elements from a list into a combined object.
26+
27+
{% highlight coffeescript %}
28+
people =
29+
{ name: '', age: 10 }
30+
{ name: '', age: 16 }
31+
{ name: '', age: 17 }
32+
33+
people.reduce (x, y) ->
34+
x[y.name]= y.age
35+
x
36+
, {}
37+
# => { alec: 10, bert: 16, chad: 17 }
38+
{% endhighlight %}
39+
40+
h2. Discussion
41+
42+
Javascript introduced <code>reduce</code> and <code>reduceRight</code> in version 1.8. Coffeescript provides a natural and simple way to express anonymous functions. Both go together cleanly in the problem of merging a collection's items into a combined result.
43+
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
layout: recipe
3+
title: Singleton Pattern
4+
chapter: Design Patterns
5+
---
6+
7+
h2. Problem
8+
9+
Many times you only want one, and only one, instance of a class. For example, you may only need one class that creates server resources and you want to ensure that the one object can control those resources. Beware, however, because the singleton pattern can be easily abused to mimic unwanted global variables.
10+
11+
h2. Solution
12+
13+
The publically available class only contains the method to get the one true instance. The instance is kept within the closure of that public object and is always returned
14+
15+
The actual definition of the singleton class follows.
16+
17+
Note that I am using the idiomatic module export feature to emphasize the publically accessible portion of the module. Remember coffeescript wraps all files in a function block to protect the global namespace
18+
19+
{% highlight coffeescript %}
20+
root = exports ? this # http://stackoverflow.com/questions/4214731/coffeescript-global-variables
21+
22+
# The publically accessible Singleton fetcher
23+
class root.Singleton
24+
_instance = undefined # Must be declared here to force the closure on the class
25+
@get: (args) -> # Must be a static method
26+
_instance ?= new _Singleton args
27+
28+
# The actual Singleton class
29+
class _Singleton
30+
constructor: (@args) ->
31+
32+
echo: ->
33+
@args
34+
35+
a = root.Singleton.get 'Hello A'
36+
a.echo()
37+
# => 'Hello A'
38+
39+
b = root.Singleton.get 'Hello B'
40+
a.echo()
41+
# => 'Hello A'
42+
43+
b.echo()
44+
# => 'Hello A'
45+
46+
root.Singleton._instance
47+
# => undefined
48+
49+
root.Singleton._instance = 'foo'
50+
51+
root.Singleton._instance
52+
# => 'foo'
53+
54+
c = root.Singleton.get 'Hello C'
55+
c.foo()
56+
# => 'Hello A'
57+
58+
a.foo()
59+
# => 'Hello A'
60+
{% endhighlight %}
61+
62+
h2. Discussion
63+
64+
See in the above example how all instances are outputting from the same instance of the Singleton class
65+
66+
Note how incredibly simple coffeescript makes this design pattern. For reference and discussion on nice javascript implementations, check out http://addyosmani.com/resources/essentialjsdesignpatterns/book/

chapters/jquery/plugin.textile

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
layout: recipe
3+
title: Create a jQuery plugin
4+
chapter: jQuery
5+
---
6+
7+
h2. Problem
8+
9+
You'd like to create jQuery plugin using CoffeeScript
10+
11+
h2. Solution
12+
13+
{% highlight coffeescript %}
14+
# Reference jQuery
15+
$ = jQuery
16+
17+
# Adds plugin object to jQuery
18+
$.fn.extend
19+
# Change pluginName to your plugin's name.
20+
pluginName: (options) ->
21+
# Default settings
22+
settings =
23+
option1: true
24+
option2: false
25+
debug: false
26+
27+
# Merge default settings with options.
28+
settings = $.extend settings, options
29+
30+
# Simple logger.
31+
log = (msg) ->
32+
console?.log msg if settings.debug
33+
34+
# _Insert magic here._
35+
return @each ()->
36+
log "Preparing magic show."
37+
# You can use your settings in here now.
38+
log "Option 1 value: #{settings.option1}"
39+
{% endhighlight %}
40+
41+
h2. Discussion
42+
43+
h3. Usage
44+
45+
Here are a couple of examples of how to use your new plugin.
46+
47+
h4. JavaScript
48+
49+
{% highlight javascript %}
50+
$("body").pluginName({
51+
debug: true
52+
};
53+
54+
{% endhighlight %}
55+
56+
h4. CoffeeScript:
57+
58+
{% highlight coffeescript %}
59+
$("body").pluginName
60+
debug: true
61+
62+
{% endhighlight %}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
---
2+
layout: recipe
3+
title: Faster Fibonacci algorithm
4+
chapter: Math
5+
---
6+
7+
h2. Problem
8+
9+
You would like to calculate a number N in the Fibonacci sequence but want
10+
to do it quickly.
11+
12+
h2. Solution
13+
14+
The following solution (which can still be improved on) was originally
15+
talked about on Robin Houston's blog.
16+
17+
Here are a few links talking about the algorithm and ways to improve it:
18+
# <a href="http://bosker.wordpress.com/2011/04/29/the-worst-algorithm-in-the-world/">http://bosker.wordpress.com/2011/04/29/the-worst-algorithm-in-the-world/</a>
19+
# <a href="http://www.math.rutgers.edu/~erowland/fibonacci.html">http://www.math.rutgers.edu/~erowland/fibonacci.html</a>
20+
# <a href="http://jsfromhell.com/classes/bignumber">http://jsfromhell.com/classes/bignumber</a>
21+
# <a href="http://www.math.rutgers.edu/~erowland/fibonacci.html">http://www.math.rutgers.edu/~erowland/fibonacci.html</a>
22+
# <a href="http://bigintegers.blogspot.com/2010/11/square-division-power-square-root.html">http://bigintegers.blogspot.com/2010/11/square-division-power-square-root.html</a>
23+
# <a href="http://bugs.python.org/issue3451">http://bugs.python.org/issue3451</a>
24+
25+
This code is in gist form here:
26+
<a href="https://gist.github.com/1032685">https://gist.github.com/1032685</a>
27+
28+
{% highlight coffeescript %}
29+
###
30+
Author: Jason Giedymin <jasong _a_t_ apache -dot- org>
31+
http://www.jasongiedymin.com
32+
https://github.com/JasonGiedymin
33+
34+
This CoffeeScript Javascript Fast Fibonacci code is
35+
based on the python code from Robin Houston's blog.
36+
See below links.
37+
38+
A few things I want to introduce in time are implementions of
39+
Newtonian, Burnikel / Ziegler, and Binet's algorithms on top
40+
of a Big Number framework.
41+
42+
Todo:
43+
- https://github.com/substack/node-bigint
44+
- BZ and Newton mods.
45+
- Timing
46+
47+
48+
###
49+
50+
MAXIMUM_JS_FIB_N = 1476
51+
52+
fib_bits = (n) ->
53+
#Represent an integer as an array of binary digits.
54+
55+
bits = []
56+
while n > 0
57+
[n, bit] = divmodBasic(n, 2)
58+
bits.push(bit)
59+
60+
bits.reverse()
61+
return bits
62+
63+
fibFast = (n) ->
64+
#Fast Fibonacci
65+
66+
if n < 0
67+
console.log "Choose an number >= 0"
68+
return
69+
70+
[a, b, c] = [1, 0, 1]
71+
72+
for bit in fib_bits(n)
73+
if bit
74+
[a, b] = [(a+c)*b, b*b + c*c]
75+
else
76+
[a, b] = [a*a + b*b, (a+c)*b]
77+
78+
c = a + b
79+
return b
80+
81+
divmodNewton = (x, y) ->
82+
throw new Error "Method not yet implemented yet."
83+
84+
divmodBZ = () ->
85+
throw new Error "Method not yet implemented yet."
86+
87+
divmodBasic = (x, y) ->
88+
###
89+
Absolutely nothing special here. Maybe later versions will be Newtonian or
90+
Burnikel / Ziegler _if_ possible...
91+
###
92+
93+
return [(q = Math.floor(x/y)), (r = if x < y then x else x % y)]
94+
95+
start = (new Date).getTime();
96+
calc_value = fibFast(MAXIMUM_JS_FIB_N)
97+
diff = (new Date).getTime() - start;
98+
console.log("[#{calc_value}] took #{diff} ms.")
99+
{% endhighlight %}
100+
101+
h2. Discussion
102+
103+
Questions?

wanted-recipes.textile

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,6 @@ h2. Strings
2626

2727
h2. Arrays
2828

29-
* Reducing arrays to values (ruby inject) with reduce # [1..10].reduce (a,b) -> a+b # 55
30-
* Reducing arrays in reverse order # JS reduceRight
31-
{% highlight coffeescript %}
32-
["example", "contrived ", "pretty ", "a ", "is ", "here "].reduceRight (x,y) -> x+y
33-
# => 'here is a pretty contrived example'
34-
{% endhighlight %}
3529
* Testing every element in an array
3630
{% highlight coffeescript %}
3731
evens = (x for x in [0..10] by 2)

0 commit comments

Comments
 (0)