Created
February 16, 2011 12:26
-
-
Save smrchy/829288 to your computer and use it in GitHub Desktop.
Create an easy to use object from a Redis sorted set
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
| // ## redisZsetWorker | |
| // Requires Underscore.js | |
| // http://documentcloud.github.com/underscore/ | |
| // | |
| // Creates an easy to use object from a Redis sorted set. | |
| // | |
| // * Calculate to total, min and max of all scores | |
| // * Calculate a font size (default: 1-10) to create a tag cloud | |
| // * Calculate the percentage for each item | |
| // | |
| // Input: A Redis sorted set: zrevrange key 0 -1 WITHSCORES | |
| // `["apples","12","oranges","8","bananas","4"]` | |
| // | |
| // The reply looks like this: | |
| // | |
| // {total:24, minv: 4, maxv: 12, rows: [ | |
| // { n: "apples", | |
| // v: 12, | |
| // p: 0.5, | |
| // s: 10}, | |
| // ... | |
| // ]} | |
| // | |
| // The rows array contains: | |
| // | |
| // * n : the item - usually a string | |
| // * v : the total value for this this item | |
| // * p : the percentage | |
| // * s : the font size | |
| redisZsetWorker = function (v, steps) { | |
| var o = { total: 0, minv: 9999999, maxv: 0, rows: [] }, | |
| steps = arguments.length > 1 ? steps : 10; | |
| _.each(v, function (e, i) { | |
| if (i%2) { | |
| e = Number(e); | |
| if (e > o.maxv) o.maxv = e; | |
| if (e < o.minv) o.minv = e; | |
| o.rows.push({ n: v[i-1], v: e }); | |
| o.total = o.total + e; | |
| } | |
| }) | |
| // Now that we have the total calculate p (the percentage) | |
| // and set s (the font size) depending on the steps | |
| // You might want to use `s` for class names like `tagsizeX` where `X` is `s` | |
| _.each(o.rows, function (e) { | |
| e.p = Math.round(e.v / o.total * 1000) / 1000; | |
| e.s = Math.ceil(Math.log(e.v) / Math.log(o.maxv) * (steps - 1) + 1); | |
| }); | |
| return o; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment