Skip to content

Commit

Permalink
Create individual file for add function
Browse files Browse the repository at this point in the history
  • Loading branch information
gsantiago committed Jan 6, 2017
1 parent 2950a07 commit 7487181
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 30 deletions.
46 changes: 46 additions & 0 deletions lib/add.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Module dependencies.
*/

var toMS = require('./toMS')
var toSrtTime = require('./toSrtTime')

/**
* Adds a new caption into the array of subtitles.
* @param {Array} subtitles
* @param {Object} caption
* @return {Array} subtitles
*/

module.exports = function add (subtitles, caption) {
if (!caption.start || !caption.end || !caption.text) {
throw new Error('Invalid caption data')
}

for (var prop in caption) {
if (!caption.hasOwnProperty(prop) || prop === 'text') {
continue
}

if (prop === 'start' || prop === 'end') {
if (/^(\d{2}):(\d{2}):(\d{2}),(\d{3})$/.test(caption[prop])) {
continue
}
if (/^\d+$/.test(caption[prop])) {
caption[prop] = toSrtTime(caption[prop])
} else {
throw new Error('Invalid caption time format')
}
}
}

subtitles.push({
index: subtitles.length + 1,
start: caption.start,
end: caption.end,
duration: toMS(caption.end) - toMS(caption.start),
text: caption.text
})

return subtitles
}
34 changes: 4 additions & 30 deletions subtitle.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var parse = require('./lib/parse')
var stringify = require('./lib/stringify')
var resync = require('./lib/resync')
var getSubtitles = require('./lib/getSubtitles')
var add = require('./lib/add')

/**
* @constructor
Expand Down Expand Up @@ -64,37 +65,10 @@ fn.parse = function _parse (srt) {
*
* @public
* @param {Object} Caption data
*/
fn.add = function (caption) {
if (!caption.start || !caption.end || !caption.text) {
throw new Error('Invalid caption data')
}

for (var prop in caption) {
if (!caption.hasOwnProperty(prop) || prop === 'text') {
continue
}

if (prop === 'start' || prop === 'end') {
if (/^(\d{2}):(\d{2}):(\d{2}),(\d{3})$/.test(caption[prop])) {
continue
}
if (/^\d+$/.test(caption[prop])) {
caption[prop] = Subtitle.toSrtTime(caption[prop])
} else {
throw new Error('Invalid caption time format')
}
}
}

this._subtitles.push({
index: this._subtitles.length + 1,
start: caption.start,
end: caption.end,
duration: Subtitle.toMS(caption.end) - Subtitle.toMS(caption.start),
text: caption.text
})
*/

fn.add = function _add (caption) {
add(this._subtitles, caption)
return this
}

Expand Down

0 comments on commit 7487181

Please sign in to comment.