From cbe4589476d419553fa272c63779be0ed957fbed Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Tue, 10 Mar 2020 10:46:12 +0100 Subject: [PATCH] function to copy objects --- README.md | 6 ++++++ index.js | 14 +++++++++++++- test/index.js | 8 ++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 672093b..b611d7b 100644 --- a/README.md +++ b/README.md @@ -11,4 +11,10 @@ util.truncate_decimal(12.345678, 2); // will return null instead of throwing on invalid json util.try_parse_json('{{foo'); + +// copy an object to prevent modification of the original +const obj = {foo:'bar'}; +const copy = util.copy_object(obj); +copy.foo = 'baz'; +console.log(obj.foo); // bar ``` diff --git a/index.js b/index.js index cff0c8f..74d5ef7 100644 --- a/index.js +++ b/index.js @@ -32,7 +32,19 @@ function try_parse_json (text) { return null; } + +/** + * copy an object to prevent modification to the original + * + * @param {object} obj object to copy + * @returns {object} copy + */ +function copy_object (obj) { + return JSON.parse (JSON.stringify (obj)); +} + module.exports = { truncate_decimal, - try_parse_json + try_parse_json, + copy_object }; diff --git a/test/index.js b/test/index.js index faca10e..92b2860 100644 --- a/test/index.js +++ b/test/index.js @@ -30,3 +30,11 @@ test ('try_parse_json should fail', (t) => { t.is (json, null); }); }); + +test ('copy object', (t) => { + const obj = {foo:'bar'}; + const copy = util.copy_object(obj); + copy.foo = 'baz'; + t.is(copy.foo, 'baz'); + t.is(obj.foo, 'bar'); +});