Skip to content

Instantly share code, notes, and snippets.

@frhd
Last active August 29, 2015 13:56
Show Gist options
  • Save frhd/8998392 to your computer and use it in GitHub Desktop.
Save frhd/8998392 to your computer and use it in GitHub Desktop.
CoffeeScript One Liners
# @ricardo.cc
# Multiply each item in a list by 2
[1..10].map (i) -> i*2
# or
i * 2 for i in [1..10]
# Sum a list of numbers
[1..1000].reduce (t, s) -> t + s
# Verify if word exists in string
wordList = ["coffeescript", "eko", "play framework", "and stuff", "falsy"]
tweet = "This is an example tweet talking about javascript and stuff."
wordList.some (word) -> ~tweet.indexOf word
wordList.filter (word) -> ~tweet.indexOf word
# Read in a File
fs.readFile 'data.txt', (err, data) -> fileText = data
# synch version:
fileText = fs.readFileSync('data.txt').toString()
# Happy Birthday
[1..4].map (i) -> console.log "Happy Birthday " + (if i is 3 then "dear Robert" else "to You")
console.log "Happy Birthday #{if i is 3 then "dear Robert" else "to You"}" for i in [1..4]
# Filter list of numbers
#iterate way
(if score > 60 then (passed or passed = []) else (failed or failed = [])).push score for score in [49, 58, 76, 82, 88, 90]
#functional
[passed, failed] = [49, 58, 76, 82, 88, 90].reduce ((p,c,i) -> p[+(c < 60)].push c; p), [[],[]]
# Fetch and Parse a XML web service
request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = body
# Find minimum (or maximum) in a List
Math.max.apply @, [14, 35, -7, 46, 98] # 98
Math.min.apply @, [14, 35, -7, 46, 98] # -7
# Sieve of Eratosthenes
primes = []
primes.push i for i in [2..100] when not (j for j in primes when i % j == 0).length
(n) -> (p.push i for i in [2..n] when !(p or p=[]).some((j) -> i%j is 0)) and n in p
#fizzbuzz
#1
"#{if i%3 is 0 then 'fizz' else ''}#{if i%5 is 0 then 'buzz' else ''}" or i for i in [1..100]
#2
['fizz' unless i%3] + ['buzz' unless i%5] or i for i in [1..100]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment