Last active
December 11, 2015 00:29
-
-
Save maninalift/4516998 to your computer and use it in GitHub Desktop.
These are a couple of utility functions I have found useful and was surprised not to find equivalents in underscore, I'm sure it's not a new idea.EDIT: two mins later I find prelude.ls does include a function covering at least the boolean case, but using an array output instead of an object. http://gkz.github.com/prelude-ls/#f-partitionEDIT2: An…
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
{map, partition, obj-to-func, sort} = require \prelude-ls | |
{render, div, h1, p} = require \teacup | |
say = console.log | |
# UTILITIES # | |
categorize_orig = (f, a) --> | |
r = {} | |
for v in a | |
k = f v | |
r.(k) ?= [] | |
r.(k).push v | |
r | |
# EDIT: re-written to match prelude.ls style | |
categorize = (f, xs) --> | |
f = obj-to-func f if typeof! f isnt \Function | |
type = typeof! xs | |
result = {} | |
if type is \Object | |
for key, x of xs | |
category = f x | |
result[category] ?= {} | |
result[category][key] = x | |
else | |
for v in xs | |
k = f v | |
result.(k) ?= [] | |
result.(k).push v | |
result | |
# a special case of categorize for functions with boolean output | |
# which guarantees both "true" and "false" | |
divide = (f, a) --> | |
r = {true: [], false: []} | |
for v in a | |
r.(f v).push v | |
r | |
words = <[foggerty another load of twoddle written from what when it was writ on this day | |
to say it was and such to do the easy lettering of love understandably | |
callous jingling under the merry tree]> | |
# quick sort | |
qs_old = ([h,...t]:a)-> if a.length<=1 then a else (divide (<h), t |> map qs |> (x)-> x.true+++[h]+++x.false ) | |
# EDIT: using the prelude.ls "partition" function | |
qs = ([h,...t]:a)-> if a.length<=1 then a else (partition (<h), t |> map qs |> (x)-> x.0+++[h]+++x.1 ) | |
say qs words | |
say render -> for l, ws of (words |> sort |> categorize (.0.to-upper-case!)) then (h1 l; p ws.join ", ") |
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
// Fire-off from Node | |
require("LiveScript"); | |
require("./cleaver"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment