From f3fbf138c8b5bf7ee91ecaf5f06f5e30dab20091 Mon Sep 17 00:00:00 2001 From: Shubham Padkonde Date: Sat, 3 Oct 2026 10:56:44 +0530 Subject: [PATCH] fix: ignore functions without mutating input objects --- index.js | 21 ++++----------------- test/unit/serialize.js | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/index.js b/index.js index 8ddc89b..2dfa46c 100644 --- a/index.js +++ b/index.js @@ -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 = {}); @@ -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; } @@ -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) + '__@'; } diff --git a/test/unit/serialize.js b/test/unit/serialize.js index 3d4de00..3bd629a 100644 --- a/test/unit/serialize.js +++ b/test/unit/serialize.js @@ -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]');