combine pad functions, test a couple branches of pad

This commit is contained in:
Sami Samhuri 2011-06-07 19:15:19 -07:00
parent 607d1f075a
commit 0bb759d406
2 changed files with 29 additions and 28 deletions

View file

@ -37,31 +37,6 @@
, PM: 'PM'
}
function pad(n, padding) {
padding = padding || '0';
return n < 10 ? (padding + n) : n;
}
function pad3(n, padding) {
padding = padding || '0';
if (n < 10) {
return padding + padding + n;
}
else if (n < 100) {
return padding + n;
}
else {
return n;
}
}
function hours12(d) {
var hour = d.getHours();
if (hour == 0) hour = 12;
else if (hour > 12) hour -= 12;
return hour;
}
function strftime(fmt, d, locale) {
return _strftime(fmt, d, locale, false);
}
@ -107,6 +82,7 @@
case 'H': return pad(d.getHours());
case 'I': return pad(hours12(d));
case 'k': return pad(d.getHours(), ' ');
case 'L': return pad(Math.floor(d.getTime() % 1000), 3);
case 'l': return pad(hours12(d), ' ');
case 'M': return pad(d.getMinutes());
case 'm': return pad(d.getMonth() + 1);
@ -116,7 +92,6 @@
case 'r': return strftime(locale.formats.r || '%I:%M:%S %p', d, locale);
case 'S': return pad(d.getSeconds());
case 's': return Math.floor((d.getTime() - msDelta) / 1000);
case 'L': return pad3(Math.floor(d.getTime() % 1000));
case 'T': return strftime(locale.formats.T || '%H:%M:%S', d, locale);
case 't': return '\t';
case 'u':
@ -149,4 +124,29 @@
});
}
// Default padding is '0' and default length is 2, both are optional.
function pad(n, padding, length) {
// pad(n, <length>)
if (typeof padding === 'number') {
length = padding;
padding = '0';
}
// Defaults handle pad(n) and pad(n, <padding>)
padding = padding || '0';
length = length || 2;
var s = String(n);
while (s.length < length) s = padding + s;
return s;
}
function hours12(d) {
var hour = d.getHours();
if (hour == 0) hour = 12;
else if (hour > 12) hour -= 12;
return hour;
}
}());

View file

@ -4,10 +4,10 @@ var assert = require('assert')
, lib = require('./../lib')
// Tue, 07 Jun 2011 18:51:45 GMT
, Time = new Date(1307472705867)
, Time = new Date(1307472705067)
, Tests =
[ { format: '%L', expected: '867' }
[ { format: '%L', expected: '067' }
, { format: '%Y', expected: '2011' }
, { format: '%m', expected: '06' }
, { format: '%b', expected: 'Jun' }
@ -17,6 +17,7 @@ var assert = require('assert')
, { format: '%M', expected: '51' }
, { format: '%S', expected: '45' }
, { format: '%s', expected: '1307472705' }
, { format: '%l', expected: null, expectedUTC: ' 6' }
]
Tests.forEach(function(t) {