leftpad (v2)

Revision 2 of this benchmark created on


Setup

function leftpad (str, len, ch) {
    str = String(str);
  
    var i = -1;
  
    if (!ch && ch !== 0) ch = ' ';
  
    len = len - str.length;
  
    while (++i < len) {
      str = ch + str;
    }
  
    return str;
  }
  
  function leftpad2(str, len, ch) {
    if (!ch && ch !== 0) ch = ' ';
    return (''+ch).repeat(Math.max(0, len - str.length)) + str
  }

Test runner

Ready to run.

Testing in
TestOps/sec
while loop
leftpad('x', 40, 'hello world')
ready
repeat and slice
leftpad2('x', 40, 'hello world')
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.