Created
June 8, 2013 12:32
-
-
Save kanghyojun/5735020 to your computer and use it in GitHub Desktop.
scala groupBy in Coffeescript
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
| a = [ | |
| {'id': 1, 'ca': 123}, {'id': 2, 'ca': 321}, {'id': 3, 'ca': 213} | |
| ] | |
| Array.prototype.groupBy = (key, callback) -> | |
| res = {} | |
| if key is undefined | |
| throw "key cannot be undefined. you MUST define key function." | |
| for i in this | |
| do (i) -> | |
| k = key(i) | |
| if typeof(k) isnt "string" | |
| throw "key must return `string`" | |
| if !res.hasOwnProperty(k) | |
| res[k] = [] | |
| res[k].push(i) | |
| callback(res) | |
| keyFunc = (i) -> | |
| r = i.ca % 100 | |
| parseInt(r / 10).toString() | |
| a.groupBy keyFunc, (r) -> | |
| console.log(r) # { '1': [ { id: 3, ca: 213 } ], '2': [ { id: 1, ca: 123 }, { id: 2, ca: 321 } ] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment