Created
August 25, 2015 08:05
-
-
Save stvvt/2525e0b6b94a7b4eaf43 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require("fs"); | |
var monMap = { | |
'Jan': 1, | |
'Feb': 2, | |
'Mar': 3, | |
'Apr': 4, | |
'May': 5, | |
'Jun': 6, | |
'Jul': 7, | |
'Aug': 8, | |
'Sep': 9, | |
'Oct': 10, | |
'Nov': 11, | |
'Dec': 12 | |
}; | |
function toNum(dateStr) { | |
var p = dateStr.split(' '); | |
return parseInt(p[1], 10) + monMap[p[0]] / 100; | |
} | |
function Range(rangeStr) { | |
var rangeArr = rangeStr.split('-'); | |
this.start = toNum(rangeArr[0]); | |
this.end = toNum(rangeArr[1]); | |
} | |
Range.create = function (rangeStr) { | |
return new Range(rangeStr); | |
} | |
Range.prototype.months = function () { | |
var ydiff = Math.floor(this.end) - Math.floor(this.start); | |
var mstart = Math.floor((this.start - Math.floor(this.start)) * 100); | |
var mend = Math.floor((this.end - Math.floor(this.end)) * 100); | |
return mend - mstart + 1 + ydiff * 12; | |
}; | |
Range.prototype.compare = function (range) { | |
if (this.start < range.start) { | |
return -1; | |
} else if (this.start > range.start) { | |
return 1; | |
} | |
return 0; | |
}; | |
Range.prototype.merge = function (range) { | |
if (range.end >= this.start && range.start <= this.end) { | |
this.start = Math.min(this.start, range.start); | |
this.end = Math.max(this.end, range.end); | |
return true; | |
} | |
return false; | |
}; | |
function lineToRanges(line) { | |
return line.split('; ') | |
.map(Range.create); | |
} | |
function rangesToMonths(ranges) { | |
return ranges | |
.sort(function (r1, r2) { | |
return r1.compare(r2); | |
}) | |
.reduce(function (acc, range) { | |
for (var i = 0; i < acc.length; i++) { | |
if (acc[i].merge(range)) { | |
range = undefined; | |
break; | |
} | |
} | |
if (range) { | |
acc.push(range); | |
} | |
return acc; | |
}, []) | |
.reduce(function (months, range) { | |
return months + range.months(); | |
}, 0) | |
; | |
} | |
function monthsToYears(months) { | |
return Math.floor(months / 12); | |
} | |
fs | |
.readFileSync(process.argv[2]) | |
.toString() | |
.split('\n') | |
.filter(function (line) { | |
return line.trim() !== ''; | |
}) | |
.map(lineToRanges) | |
.map(rangesToMonths) | |
.map(monthsToYears) | |
.forEach(function (years) { | |
console.log(years); | |
}) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment