index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* This program is free software. It comes without any warranty, to
  2. * the extent permitted by applicable law. You can redistribute it
  3. * and/or modify it under the terms of the Do What The Fuck You Want
  4. * To Public License, Version 2, as published by Sam Hocevar. See
  5. * http://www.wtfpl.net/ for more details. */
  6. 'use strict';
  7. module.exports = leftPad;
  8. var cache = [
  9. '',
  10. ' ',
  11. ' ',
  12. ' ',
  13. ' ',
  14. ' ',
  15. ' ',
  16. ' ',
  17. ' ',
  18. ' '
  19. ];
  20. function leftPad (str, len, ch) {
  21. // convert `str` to a `string`
  22. str = str + '';
  23. // `len` is the `pad`'s length now
  24. len = len - str.length;
  25. // doesn't need to pad
  26. if (len <= 0) return str;
  27. // `ch` defaults to `' '`
  28. if (!ch && ch !== 0) ch = ' ';
  29. // convert `ch` to a `string` cuz it could be a number
  30. ch = ch + '';
  31. // cache common use cases
  32. if (ch === ' ' && len < 10) return cache[len] + str;
  33. // `pad` starts with an empty string
  34. var pad = '';
  35. // loop
  36. while (true) {
  37. // add `ch` to `pad` if `len` is odd
  38. if (len & 1) pad += ch;
  39. // divide `len` by 2, ditch the remainder
  40. len >>= 1;
  41. // "double" the `ch` so this operation count grows logarithmically on `len`
  42. // each time `ch` is "doubled", the `len` would need to be "doubled" too
  43. // similar to finding a value in binary search tree, hence O(log(n))
  44. if (len) ch += ch;
  45. // `len` is 0, exit the loop
  46. else break;
  47. }
  48. // pad `str`!
  49. return pad + str;
  50. }