Create a gist now

Instantly share code, notes, and snippets.

Challenge:

Write a function that accepts an integer (or bigint) number of bytes and returns the human readable format of that size. Round down to the largest unit of measurement. Must support at least up to Petabyte (PB). See the examples for more information.

Expectations:

  • the function should be of the form f(integer) => string
  • The input will be a whole number, and will be greater than 0 and no larger than 2^63-1.
  • The output will be {x} {unit} where x is a whole number and unit is one of B|KB|MB|GB|TB|PB|...

Examples:

f(1) == '1 B'
f(1024) == '1 KB'
f(1048576) == '1 MB'
f(1234567) == '1 MB'
f(9999999999) = '9 GB' 

Judging

  • Correctness of the result. The solution must address the problem as specified.
  • Readability. This is not code golf - conciseness is good, but readable/understandable/maintainable is the goal.
  • Bonus points for including unit tests.
  • Further bonus points for sharing unit tests in the comments on the gist.

Rules

  • Original work only.
  • Submissions should be licensed under a permissive license (MIT/BSD/Apache 2.0/etc.)
  • You can use any language.
  • This is for fun and learning. There are no prizes except pride, knowledge and maybe karma.
  • Submit answers in the comments of the gist as a link Gist/PasteBin/Online REPL, not in slack.
  • Feel free to discuss the problem and solutions in cfml-slack in #friday-puzzle.
  • If you need to clarify something about the problem or rules, do it here in the comments on the gist, or at least copy the clarification here for posterity