Skip to content

Instantly share code, notes, and snippets.

@smrchy
Created May 6, 2013 09:39
Show Gist options
  • Select an option

  • Save smrchy/5524228 to your computer and use it in GitHub Desktop.

Select an option

Save smrchy/5524228 to your computer and use it in GitHub Desktop.
Redis ZSET Worker To create an easy to use object for statistics
# ## 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 = (v, steps) ->
o = { total: 0, minv: 9999999, maxv: 0, rows: [] }
steps = if arguments.length > 1 then steps else 12
for e,i in v
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`
for e in o.rows
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)
o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment