Last active
December 27, 2015 10:19
-
-
Save moimikey/7310211 to your computer and use it in GitHub Desktop.
calculate data transfer bits
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
# 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