number_utils.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with this
  4. * work for additional information regarding copyright ownership. The ASF
  5. * licenses this file to you under the Apache License, Version 2.0 (the
  6. * "License"); you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. module.exports = {
  18. /**
  19. * Convert byte size to other metrics.
  20. *
  21. * @param {Number} Bytes to convert to string
  22. * @param {Number} Precision Number to adjust precision of return value. Default is 0.
  23. * @param {String}
  24. * parseType JS method name for parse string to number. Default is
  25. * "parseInt".
  26. * @param {Number} Multiplies bytes by this number if given. This is needed
  27. * as <code>null * 1024 = 0</null>
  28. * @remarks The parseType argument can be "parseInt" or "parseFloat".
  29. * @return {String) Returns converted value with abbreviation.
  30. */
  31. bytesToSize: function (bytes, precision, parseType/* = 'parseInt' */, multiplyBy) {
  32. if (bytes === null || bytes === undefined) {
  33. return 'n/a';
  34. } else {
  35. if (arguments[2] === undefined) {
  36. parseType = 'parseInt';
  37. }
  38. if (arguments[3] === undefined) {
  39. multiplyBy = 1;
  40. }
  41. var value = bytes * multiplyBy;
  42. var sizes = [ 'Bytes', 'KB', 'MB', 'GB', 'TB', 'PB' ];
  43. var posttxt = 0;
  44. while (value >= 1024) {
  45. posttxt++;
  46. value = value / 1024;
  47. }
  48. if (value === 0) {
  49. precision = 0;
  50. }
  51. var parsedValue = window[parseType](value);
  52. return parsedValue.toFixed(precision) + " " + sizes[posttxt];
  53. }
  54. }
  55. };