From 0bb759d40609e0c812437b5f17cab4eb2fe7c22d Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Tue, 7 Jun 2011 19:15:19 -0700 Subject: [PATCH] combine pad functions, test a couple branches of pad --- lib/index.js | 52 ++++++++++++++++++++++++++-------------------------- test/test.js | 5 +++-- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/lib/index.js b/lib/index.js index 9c2c172..661a0b0 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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, ) + if (typeof padding === 'number') { + length = padding; + padding = '0'; + } + + // Defaults handle pad(n) and pad(n, ) + 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; + } + }()); \ No newline at end of file diff --git a/test/test.js b/test/test.js index df19d9f..618705c 100644 --- a/test/test.js +++ b/test/test.js @@ -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) {