Last active
May 9, 2016 16:58
-
-
Save luk3thomas/978b14d884878e8e7ccf to your computer and use it in GitHub Desktop.
This file contains 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
toArray = (d) -> [].slice.call(d) | |
currify = (fn, args, remaining)-> | |
if remaining < 1 | |
return fn.apply(null, args) | |
-> | |
currify(fn, args.slice(0, fn.length - 1).concat(toArray(arguments)), remaining - arguments.length) | |
curry = (fn) -> | |
-> | |
currify(fn, toArray(arguments), fn.length - arguments.length) | |
module.exports = | |
curry: curry | |
get: curry (property, object) -> | |
object[property] | |
pick: curry (properties, object) -> | |
if typeof properties is "string" | |
properties = [properties] | |
tmp = {} | |
tmp[k] = v for k,v of object when properties.indexOf(k) > -1 | |
tmp | |
total: (m, n) -> m + n | |
average: (m, n, i, list) -> | |
if i is list.length - 1 | |
(m + n) / list.length | |
else | |
m + n |
This file contains 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
{curry, get, pick, total, average} = require "server/utils/functional" | |
sum = | |
data = null | |
describe "functional", -> | |
beforeEach -> | |
data = [ | |
name: "Foo" | |
value: 1 | |
year: 1970 | |
, | |
name: "Bar" | |
value: 2 | |
year: 1971 | |
, | |
name: "Qux" | |
value: 3 | |
year: 1972 | |
] | |
sum = curry (a, b, c, d) -> a + b + c + d | |
describe "#curry", -> | |
it "works in any order", -> | |
expect(sum(1,2,3,4)) .toBe 10 | |
expect(sum(1,2)(3)(4)) .toBe 10 | |
expect(sum(1)(2,3,4)) .toBe 10 | |
expect(sum(1)(2)(3)(4)) .toBe 10 | |
it "returns original function if all args exist", -> | |
name = get("name", data[0]) | |
expect(name).toBe "Foo" | |
it "returns a function", -> | |
name = get("name") | |
expect(name(data[0])).toBe "Foo" | |
expect(name(data[1])).toBe "Bar" | |
expect(name(data[2])).toBe "Qux" | |
describe "#get", -> | |
it "combines with map", -> | |
names = data.map(get("name")) | |
expect(names).toEqual ["Foo", "Bar", "Qux"] | |
describe "#pick", -> | |
it "combines with map", -> | |
names = data.map(pick(["name", "year"])) | |
expect(names).toEqual [ | |
name: "Foo" | |
year: 1970 | |
, | |
name: "Bar" | |
year: 1971 | |
, | |
name: "Qux" | |
year: 1972 | |
] | |
describe "#average", -> | |
it "averages with reduce", -> | |
expect(data.map(get("value")).reduce(average)).toBe 2 | |
describe "#total", -> | |
it "totals with reduce", -> | |
expect(data.map(get("value")).reduce(total)).toBe 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment