Skip to content

Instantly share code, notes, and snippets.

@gustafnk
Created November 27, 2010 12:31
Show Gist options
  • Save gustafnk/717856 to your computer and use it in GitHub Desktop.
Save gustafnk/717856 to your computer and use it in GitHub Desktop.
Playing with CoffeeScript and underscore.coffee
# Check CoffeeScript
square = (x) -> x * x
puts "'2' squared: #{square 2}"
# See if underscore.coffee is loaded
puts "underscore version: #{_.VERSION}"
# Some printing utility functions
printArray = (name, xs) -> puts "'#{name}': [#{xs}]"
printArraySize = (name, xs) -> puts "'#{name}' has #{_.size xs} elements"
printArrayAndItsSize = (name, xs) ->
printArray name, xs
printArraySize name, xs
yesNo = (b) -> if b then "Yes" else "No"
# Define some arrays
xs = [1..100]
printArraySize "xs", xs
tens = [1..10]
printArray "tens", tens
# Return all but the last element in an array
init = (xs) -> xs[0...(_.size xs.length) - 1]
printArray "init tens", init tens
# Naive functions for working with tuples as arrays
fst = (tp) -> tp[0]
snd = (tp) -> tp[1]
# Nice example of using _.zip, _.tail, ._map, and _.all
isConsecutive = (xs) ->
xsInit = init xs
xsRest = _.tail xs
xsZip = _.zip xsInit, xsRest
_.all _.map xsZip, (tp) -> (fst tp) + 1 == (snd tp)
puts "Is tens consecutive? #{yesNo isConsecutive tens}"
nonConsecutive = [1..4].concat [6..10]
printArray "nonConsecutive", nonConsecutive
puts "Is nonConsecutive consecutive? #{yesNo isConsecutive nonConsecutive}"
# Returns true if argument is even
even = (n) -> n % 2 == 0
anEvenNumber = 10
anOddNumber = 9
evenNumberUI = (n) -> puts "Is #{n} an even number? #{yesNo even n}"
evenNumberUI anEvenNumber
evenNumberUI anOddNumber
# Returns all even numbers from an array
evens = (ys) -> _.filter ys, even
printArraySize "evens xs", (evens xs)
---- OUTPUT ----
'2' squared: 4
underscore version: 1.1.0
'xs' has 100 elements
'tens': [1,2,3,4,5,6,7,8,9,10]
'init tens': [1,2,3,4,5,6,7,8,9]
Is tens consecutive? Yes
'nonConsecutive': [1,2,3,4,6,7,8,9,10]
Is nonConsecutive consecutive? No
Is 10 an even number? Yes
Is 9 an even number? No
'evens xs' has 50 elements
---- A naive 'build script'. I need to learn how to do this in reality... ----
cat underscore.coffee > tmp____.coffee
cat world.coffee >> tmp____.coffee
coffee tmp____.coffee
rm tmp____.coffee
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment