Share your code. Components are building blocks, you are the architect.

string/left-pad
v1.0.0
1.0.0
0.0.1
MIT
PUBLIC
49
0     DEPENDENCIES
Build: pass
BuildPass
Build Status: pass
pad a string to the left.
bit
Contributors
Gravatar for undefinedGravatar for undefined
0

Please configure Bit as a scoped registry to install components with NPM.Learn more

npm config set '@bit:registry' https://node.bitsrc.io
Use string/left-pad in your project
npm i @bit/bit.utils.string.left-pad
Copied
Files
src/string/leftPad.js
45 Lines (28 sloc)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/** @flow */

const cache = [
    '',
    ' ',
    '  ',
    '   ',
    '    ',
    '     ',
    '      ',
    '       ',
    '        ',
    '         '
  ];
  
  /**
   * pad a string to the left.
   * @name leftPad
   * @param {string} str string to pad
   * @param {number} len total 
   * @param {string} ch char to use for padding
   * @returns {string} modified string
   * @example
   *  leftPad('foo', 5) // => "  foo"
   *  leftPad('foobar', 6) // => "foobar"
   *  leftPad(1, 2, '0') // => "01"
   */
  export default function leftPad(str: string, len: number, ch: string): string {
    str = str + '';
    len = len - str.length;
    if (len <= 0) return str;
    if (!ch && ch !== 0) ch = ' ';
    ch = ch + '';
    if (ch === ' ' && len < 10) return cache[len] + str;
    let pad = '';
  
    while (true) {
      if (len & 1) pad += ch;
      len >>= 1;
      if (len) ch += ch;
      else break;
    }
  
    return pad + str;
  };