Permalink
Browse files

Better documentation

  • Loading branch information...
1 parent 2ccc211 commit 75d218cebb043e24884f6f7b565db954529ff9aa @eivindfjeldstad committed Mar 21, 2013
Showing with 163 additions and 77 deletions.
  1. +143 −71 index.js
  2. +2 −0 lang/index.js
  3. +15 −2 readme.md
  4. +3 −4 test.js
View
214 index.js
@@ -1,44 +1,27 @@
var fs = require('fs')
- , path = require('path')
- , files = fs.readdirSync(path.join(__dirname, 'lang'))
- , langs = {}
- , lang
-
-files.forEach(function (filename) {
- var language = filename.replace(/\.json$/, '');
-
- langs[language] = require('./lang/' + filename);
-});
-
-var units = exports.units = {
- years : 31536000000
- , months : 2592000000
- , weeks : 604800000
- , days : 86400000
- , hours : 3600000
- , minutes : 60000
- , seconds : 1000
-};
-
-var formats = exports.formats = {};
+ , format = require('util').format
+ , langs = require('./lang')
// Set the default language
var lang = langs['en-us'];
-exports.setLang = function (language) {
- if (typeof language == 'object')
- lang = language;
- else if (langs[language])
- lang = langs[language];
-};
+// RegExp to tokenize a format string
+var TOKENS = /Y{2,4}|[Md]{1,4}|[DHhms]{1,2}|[Aa]|"[^"]*"|'[^']*'/g;
-exports.format = function (date, format) {
- var tokens = /Y{2,4}|[Md]{1,4}|[DHhms]{1,2}|[Aa]|"[^"]*"|'[^']*'/g
- , date = toObject(date);
-
+/**
+ * Format date
+ *
+ * @param {Date} date
+ * @param {String} format
+ * @return {String}
+ * @api public
+ */
+
+function dateable (date, format) {
+ var date = toObject(date);
format = formats[format] || format;
- return format.replace(tokens, function (part) {
+ return format.replace(TOKENS, function (part) {
switch (part) {
case 'YYYY':
return pad(date.Y, 3);
@@ -84,13 +67,59 @@ exports.format = function (date, format) {
});
};
-exports.parse = function (string, format) {
- var tokenizer = /Y{2,4}|[Md]{1,4}|[DHhms]{1,2}|[Aa]/g
- , offset = 0
+// Backwards compatibility
+dateable.format = dateable;
+
+// Available units
+var units = dateable.units = {
+ years : 31536000000
+ , months : 2592000000
+ , weeks : 604800000
+ , days : 86400000
+ , hours : 3600000
+ , minutes : 60000
+ , seconds : 1000
+};
+
+// Stored formats
+var formats = dateable.formats = {};
+
+/**
+ * Set language
+ *
+ * @param {String|Object} language
+ * @api public
+ */
+
+dateable.language = function (language) {
+ if (typeof language !== 'string') {
+ lang = language;
+ } else if (langs[language]) {
+ lang = langs[language];
+ }
+
+ return this;
+};
+
+// Backwards compatibility
+dateable.setLang = dateable.language;
+
+// Tokenizer for a formatted date
+var TOKENIZER = /Y{2,4}|[Md]{1,4}|[DHhms]{1,2}|[Aa]/g ;
+
+/**
+ * Parse string from format to date
+ *
+ * @param {String} string
+ * @param {String} format
+ * @return {Date}
+ * @api public
+ */
+
+dateable.parse = function (string, format) {
+ var offset = 0
, parts = {}
- , token
- , index
- , part
+ , token;
format = formats[format] || format;
// Strip the string from the escaped parts of the format
@@ -101,11 +130,11 @@ exports.parse = function (string, format) {
var stringLength = string.length;
- while (token = tokenizer.exec(format)) {
- index = token.index + offset;
+ while (token = TOKENIZER.exec(format)) {
+ var index = token.index + offset
+ , tokenLength = token[0].length
+ , part = string.substr(index, tokenLength);
- var tokenLength = token[0].length;
- part = string.substr(index, tokenLength);
index += tokenLength - 1;
// Remove characters that are not part of the format
@@ -137,7 +166,16 @@ exports.parse = function (string, format) {
return toDate(parts);
};
-exports.when = function (date, unit) {
+/**
+ * Relative time
+ *
+ * @param {Date} date
+ * @param {String} [unit]
+ * @return {String}
+ * @api public
+ */
+
+dateable.when = function (date, unit) {
var diff = date.valueOf() - Date.now()
, time = 'present'
@@ -149,10 +187,20 @@ exports.when = function (date, unit) {
diff = Math.abs(diff);
- return printify(lang.time[time], pluralize(diff, unit));
+ return format(lang.time[time], pluralize(diff, unit));
};
-exports.diff = function (start, end, unit) {
+/**
+ * Return difference between two dates
+ *
+ * @param {Date} start
+ * @param {Date} end
+ * @param {String} [unit]
+ * @return {String}
+ * @api public
+ */
+
+dateable.diff = function (start, end, unit) {
var diff = start.valueOf() - end.valueOf()
, unit = unit || determineUnit(diff)
@@ -161,47 +209,61 @@ exports.diff = function (start, end, unit) {
return pluralize(diff, unit);
};
+/**
+ * Pluralize unit
+ *
+ * @param {Number} value
+ * @param {String} unit
+ * @return {String}
+ * @api private
+ */
+
function pluralize (value, unit) {
var form = lang.units[unit][value > 1 ? 1 : 0];
-
- return printify(form, value);
+ return format(form, value);
};
-function determineUnit (ms) {
- var unit;
-
+/**
+ * Find the best matching unit for an amount of time (ms)
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function determineUnit (ms) {
ms = Math.abs(ms);
- for (unit in units) {
- if (ms > units[unit])
- break;
+ for (var unit in units) {
+ if (ms > units[unit]) break;
}
return unit;
}
-function printify (string) {
- var args = [].slice.call(arguments, 1)
- , offset = 0;
-
- return string.replace(/%s([0-9])*/g, function (s, n) {
- n = n || offset;
-
- if (args[n] && Array.isArray(args[n]))
- args[n] = printify.apply(null, args[n]);
-
- offset++;
+/**
+ * Pad a number with leading zeros
+ *
+ * @param {Number} number
+ * @param {Number} length
+ * @return {String}
+ * @api private
+ */
- return args[n];
- });
-}
-
-function pad (number, zeros) {
- return number < Math.pow(10, zeros || 1)
+function pad (number, length) {
+ return number < Math.pow(10, length || 1)
? '0' + number
: '' + number;
}
+/**
+ * Convert an object to a date
+ *
+ * @param {Object} object
+ * @return {Number} length
+ * @api private
+ */
+
function toDate (obj) {
var date = new Date(0)
, abbr = obj.a || obj.A
@@ -232,6 +294,14 @@ function toDate (obj) {
return date;
}
+/**
+ * Convert a date to an object
+ *
+ * @param {Object} date
+ * @return {Object}
+ * @api private
+ */
+
function toObject (date) {
var obj = {
Y: date.getFullYear()
@@ -250,3 +320,5 @@ function toObject (date) {
return obj;
}
+
+module.exports = dateable;
View
@@ -0,0 +1,2 @@
+exports['en-us'] = require('./en-us.json');
+exports['nb-no'] = require('./nb-no.json');
View
@@ -9,7 +9,7 @@ A small library that provides a few very useful methods for displaying dates, in
```javascript
var dateable = require('dateable');
-var str = dateable.format(new Date(), 'MM/DD-YYYY, hh:mm'); // e.g., 03/23-2012, 22:10
+var str = dateable(new Date(), 'MM/DD-YYYY, hh:mm'); // e.g., 03/23-2012, 22:10
dateable.parse(str, 'MM/DD-YYYY, hh:mm') // Returns the original date
```
@@ -20,7 +20,7 @@ If you want to include text in the formatting, just escape it with either ' or "
var date = new Date(2009, 4, 23)
, format = '"I went to the moon in" YYYY. "I think it was a" dddd "in" MMMM';
-dateable.format(date, format); // I went to the moon in 2009. I think it was a Saturday in May
+dateable(date, format); // I went to the moon in 2009. I think it was a Saturday in May
```
You can also get the answers to simple questions, such as:
@@ -36,5 +36,18 @@ dateable.when(new Date(2020, 4, 30)); // in 8 years
dateable.diff(new Date(2015), new Date()); // 3 years
```
+## API
+### dateable(date, format)
+Return formatted date
+
+### dateable#parse(date, format)
+Return original date from format
+
+### dateable#when(date, [unit])
+Returns relative date in specified or closest matching unit
+
+### dateable#language(language)
+Set language
+
## Why?
Because dealing with dates in javascript is a fucking pain in the ass!
View
@@ -8,14 +8,14 @@ var tests = module.exports = {
var date = new Date(2012, 4, 7, 16, 7, 3)
, expected = '2012 12 May May old school 05 5 07 7 Monday Mon 04 4 pm PM 16 16 07 7 03 3';
- assert.equal(dateable.format(date, 'test'), expected);
+ assert.equal(dateable(date, 'test'), expected);
},
'test parse': function () {
var date = new Date(1992, 1, 25, 7, 0, 1)
, expected = date.valueOf();
- date = dateable.format(date, 'test');
+ date = dateable(date, 'test');
assert.equal(dateable.parse(date, 'test').valueOf(), expected);
},
@@ -33,7 +33,6 @@ var tests = module.exports = {
}
};
-for (var t in tests)
- tests[t]();
+for (var t in tests) tests[t]();
console.log('All tests completed successfully');

0 comments on commit 75d218c

Please sign in to comment.