Left Padding (v3)

Revision 3 of this benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
For Loop Builds Prepend
function valueToLeftPaddedFourDigit(value) {
  if (typeof value === 'number') {
    value = String(value);
  }

  if (typeof value === 'string') {
    const pads = 4 - value.length;
    let pre = '';

    for (let i = pads; i > 0; i--) {
      pre += '0';
    }

    return `${pre}${value}`;
  }

  return value;
}

valueToLeftPaddedFourDigit('702');
ready
Prepend and Substring Difference
function valueToLeftPaddedFourDigit(value) {
  if (typeof value === 'number') {
    value = String(value);
  }

  if (typeof value === 'string') {
    const paddedValue = `000${value}`;
    const len = paddedValue.length;

    return paddedValue.substring((len - 4), len);
  }

  return value;
}

valueToLeftPaddedFourDigit('702');
ready
Prepend and Substring Difference Single Check
function valueToLeftPaddedFourDigit(value) {
  if (typeof value === 'string' || typeof value === 'number') {
    value = `000${value}`;
    const len = value.length;

    return value.substring((len - 4), len);
  }

  return value;
}

valueToLeftPaddedFourDigit('702');
ready
Prepend and Substring Difference Single Check No Last Length
function valueToLeftPaddedFourDigit(value) {
  if (typeof value === 'string' || typeof value === 'number') {
    value = `000${value}`;

    return value.substring(value.length - 4);
  }

  return value;
}

valueToLeftPaddedFourDigit('702');
ready

Revisions

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