Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active December 27, 2015 10:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/7310211 to your computer and use it in GitHub Desktop.
Save moimikey/7310211 to your computer and use it in GitHub Desktop.
calculate data transfer bits
# Convert bit rate from and to another rate
#
# amount: data being converted
# unitFrom: `from` unit. bps|kbps|mbps|gbps
# unitTo: `to` unit. bps|kbps|mbps|gbps
#
# uses double bitwise not `~~` as `Math.floor`
# uses `+` as type coercion to `int`
Util.bitCalculate = (amount, unitFrom, unitTo, maxDecimals=2) ->
base = 1000
switch unitFrom
when 'bps'
switch unitTo
when 'kbps'
result = amount / Math.pow base, 1
when 'mbps'
result = amount / Math.pow base, 2
when 'gbps'
result = amount / Math.pow base, 3
else
result = amount
when 'kbps'
switch unitTo
when 'bps'
result = amount * Math.pow base, 1
when 'mbps'
result = amount / Math.pow base, 1
when 'gbps'
result = amount / Math.pow base, 3
else
result = amount
when 'mbps'
switch unitTo
when 'bps'
result = amount * Math.pow base, 2
when 'kbps'
result = amount * Math.pow base, 1
when 'gbps'
result = amount / Math.pow base, 1
else
result = amount
when 'gpbs'
switch unitTo
when 'bps'
result = ~~(amount * Math.pow(base, 3))
when 'kbps'
result = ~~(amount * Math.pow(base, 2))
when 'mbps'
result = amount * Math.pow base, 1
else
result = amount
regex = new RegExp "\\d+\\.?\\d{#{maxDecimals}}"
"#{+String(result).match regex}#{_.capitalize(unitTo)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment