Skip to content

Commit

Permalink
feat: add formatTime function, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hexjelly committed Jan 30, 2017
1 parent 20bcb32 commit 99f3564
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/util.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
function formatTime () {
//
/**
* Converts Elmas weird int-as-string times to formatted strings.
* @param {string} str String to pad
* @param {integer} pad Amount to pad
* @returns {string} string
*/
function formatTime (time) {
time = time.toString()
let formatted = ['0', '0', ':', '0', '0', ',', '0', '0']

// If input time is longer than 6 characters, return max time?
if (time.length > 6) return '59:59,99'

let n = 7
for (let i = time.length - 1; i >= 0; i--) {
// If first digit of minutes or seconds are over 5, throw error?
if (((n === 3) || (n === 0)) && (time.charCodeAt(i) > 53)) throw new Error('Invalid time format')
formatted[n] = time[i]
if (n === 6 || n === 3) n -= 2
else if (n > 0) n -= 1
}

return formatted.join('')
}

/**
Expand Down
34 changes: 34 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -457,3 +457,37 @@ test('getTime, unfinished, single, event, framediff', t => {
/* * * * * * * *
* Util tests *
* * * * * * * */
test('nullpadString, string length longer than padding', t => {
t.is(nullpadString('teststring', 4), 'test')
})

test('nullpadString, non-ASCII string throws error', t => {
const error = t.throws(() => {
nullpadString('this is not ascii: ►', 4)
}, Error)

t.is(error.message, 'String contains non-ASCII values')
})

test('formatTime gives correct values', t => {
t.is(formatTime(114801), '11:48,01')
t.is(formatTime(10021), '01:00,21')
t.is(formatTime(10099), '01:00,99')
t.is(formatTime(590099), '59:00,99')
t.is(formatTime(1000), '00:10,00')
t.is(formatTime(0), '00:00,00')
t.is(formatTime(1922039), '59:59,99')
})

test('formatTime, invalid time format throws error', t => {
const error1 = t.throws(() => {
formatTime(601039)
}, Error)

const error2 = t.throws(() => {
formatTime(16039)
}, Error)

t.is(error1.message, 'Invalid time format')
t.is(error2.message, 'Invalid time format')
})

0 comments on commit 99f3564

Please sign in to comment.