Skip to content

Adding support for dates #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ var util = require('util');
module.exports = serialize;

var IS_NATIVE_CODE_REGEX = /\{\s*\[native code\]\s*\}/g,
PLACE_HOLDER_REGEX = /"@__(FUNCTION|REGEXP)_(\d+)__@"/g,
PLACE_HOLDER_REGEX = /"@__(FUNCTION|REGEXP|DATE)_(\d+)__@"/g,
UNSAFE_CHARS_REGEX = /[<>\/\u2028\u2029]/g;

// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
Expand All @@ -27,6 +27,7 @@ var UNICODE_CHARS = {
function serialize(obj) {
var functions = [],
regexps = [],
dates = [],
str;

// Creates a JSON string representation of the object and uses placeholders
Expand All @@ -40,6 +41,10 @@ function serialize(obj) {
if (util.isRegExp(value)) {
return '@__REGEXP_' + (regexps.push(value) - 1) + '__@';
}
// is date
if (util.isDate(value)) {
return '@__DATE_' + (dates.push(value) - 1) + '__@';
}

return value;
});
Expand All @@ -57,7 +62,7 @@ function serialize(obj) {
return UNICODE_CHARS[unsafeChar];
});

if (!(functions.length || regexps.length)) {
if (!(functions.length || regexps.length || dates.length)) {
return str;
}

Expand All @@ -69,6 +74,10 @@ function serialize(obj) {
return regexps[index].toString();
}

if (type === 'DATE') {
return 'new Date(' + dates[index].getTime() + ')';
}

var fn = functions[index],
serializedFn = fn.toString();

Expand Down