Skip to content
This repository has been archived by the owner on May 9, 2019. It is now read-only.

highly efficient solution #11

Closed
wants to merge 12 commits into from
15 changes: 9 additions & 6 deletions index.js
Expand Up @@ -3,15 +3,18 @@ module.exports = leftpad;
function leftpad (str, len, ch) {
str = String(str);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

str = '' + str;
how about?
http://jsperf.com/number-to-string/2
number to string jsperf


var i = -1;

if (!ch && ch !== 0) ch = ' ';

len = len - str.length;
if (len <=0) return str;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing whitespace before 0


while (++i < len) {
str = ch + str;
ch = ch + '';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ch += ''; ?

pad_str = '';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing var

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And it's better to use camel-style, let's say var padStr. Maybe pad is another choice.

while (true) {
if (len & 1) pad_str += ch;
len >>= 1

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing semicolon

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for those comments.

if (len) ch += ch;
else break;
}

return str;
return pad_str + str;
}
5 changes: 4 additions & 1 deletion test.js
Expand Up @@ -2,9 +2,12 @@ var leftpad = require("./");
var test = require("tape");

test('left pad', function (assert) {
assert.plan(4);
assert.plan(7);
assert.strictEqual(leftpad('foo', 5), ' foo');
assert.strictEqual(leftpad('foobar', 6), 'foobar');
assert.strictEqual(leftpad(1, 2, 0), '01');
assert.strictEqual(leftpad(1, 2, '-'), '-1');
assert.strictEqual(leftpad('foo', 2, ' '), 'foo');
assert.strictEqual(leftpad('foo', -1, ' '), 'foo');
assert.strictEqual(leftpad('foo', 7, 1), '1111foo');
});