Created
September 23, 2013 17:29
-
-
Save awagner83/6674058 to your computer and use it in GitHub Desktop.
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
_ = require 'underscore' | |
# Pure functional (with foldl and filter) | |
countZeroes1 = (xs) -> count1 (_.filter xs, (x) -> x == 0) | |
count1 = (xs) -> _.foldl xs, ((l, r) -> l + 1), 0 | |
# Pure function (with list length -- usually available in function setting) | |
countZeroes2 = (xs) -> (_.filter xs, (x) -> x == 0).length | |
# Underscore 'chain'... has some functional aspects to it | |
# (people do this sort of thing in Haskell sometimes) | |
countZeroes3 = (xs) -> | |
_.chain(xs) | |
.filter((x) -> x == 0) | |
.value() | |
.length | |
# Haskell implementation: | |
# countZeroes = length . filter (== 0) | |
# Best coffee/underscore approx: | |
countZeroes4 = _.compose _.size, ((xs) -> _.filter xs, (x) -> x == 0) | |
# Pure functional (without filter - a little ridiculous) | |
countZeroes5 = (xs) -> _.foldl xs, ((l, r) -> l + (if r == 0 then 1 else 0)), 0 | |
# implemented with count | |
# Haskell implementation: | |
# count f = length . filter f | |
# countZeroes = count (== 0) | |
count6 = (f, xs) -> _.foldl xs, ((l, r) -> l + (if (f r) then 1 else 0)), 0 | |
countZeroes6 = (xs) -> count6 ((x) -> x == 0), xs | |
# now using _.partial | |
countZeroes7 = _.partial count6, (x) -> x == 0 | |
# Let's run these! | |
input = [1, 2, 3, 0, 1, 0, 5, 0, 0] | |
console.log "countZeroes1", countZeroes1 input | |
console.log "countZeroes2", countZeroes2 input | |
console.log "countZeroes3", countZeroes3 input | |
console.log "countZeroes4", countZeroes4 input | |
console.log "countZeroes5", countZeroes5 input | |
console.log "countZeroes6", countZeroes6 input | |
console.log "countZeroes7", countZeroes7 input |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment