Skip to content
Open
Show file tree
Hide file tree
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
21 changes: 4 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,6 @@ function generateUID() {
return result;
}

function deleteFunctions(obj){
var functionKeys = [];
for (var key in obj) {
if (typeof obj[key] === "function") {
functionKeys.push(key);
}
}
for (var i = 0; i < functionKeys.length; i++) {
delete obj[functionKeys[i]];
}
}

module.exports = function serialize(obj, options) {
options || (options = {});

Expand All @@ -156,11 +144,6 @@ module.exports = function serialize(obj, options) {
// which are later replaced by their string representation.
function replacer(key, value) {

// For nested function
if(options.ignoreFunction){
deleteFunctions(value);
}

if (!value && value !== undefined && value !== BigInt(0)) {
return value;
}
Expand Down Expand Up @@ -200,6 +183,10 @@ module.exports = function serialize(obj, options) {
}

if (type === 'function') {
if (options.ignoreFunction) {
// Let JSON.stringify omit functions without mutating the input.
return value;
}
return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
}

Expand Down
21 changes: 21 additions & 0 deletions test/unit/serialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,27 @@ describe('serialize( obj )', function () {
});
});

describe('ignoring functions without changing the input', function () {
it('should preserve function properties in nested input objects', function () {
var fn = function () {};
var obj = {nested: {fn: fn, value: 1}};
strictEqual(serialize(obj, {ignoreFunction: true}), '{"nested":{"value":1}}');
strictEqual(obj.nested.fn, fn);
});

it('should accept frozen objects containing functions', function () {
var obj = Object.freeze({fn: function () {}, value: 1});
strictEqual(serialize(obj, {ignoreFunction: true}), '{"value":1}');
});

it('should replace array functions with null without deleting elements', function () {
var fn = function () {};
var values = [fn, 1];
strictEqual(serialize(values, {ignoreFunction: true}), '[null,1]');
strictEqual(values[0], fn);
});
});

describe('backwards-compatability', function () {
it('should accept `space` as the second argument', function () {
strictEqual(serialize([1], 0), '[1]');
Expand Down