From 5253091624ec2459473812d60dfb946af17fdf82 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 3 Jun 2023 23:43:12 +0200 Subject: [PATCH] =?UTF-8?q?problems(js):=20add=20=E2=80=9C2700.=20Differen?= =?UTF-8?q?ces=20Between=20Two=20Objects=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .../js/differences-between-two-objects.js | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 problems/js/differences-between-two-objects.js diff --git a/problems/js/differences-between-two-objects.js b/problems/js/differences-between-two-objects.js new file mode 100644 index 0000000..4515a10 --- /dev/null +++ b/problems/js/differences-between-two-objects.js @@ -0,0 +1,29 @@ +/** + * @param {object} obj1 + * @param {object} obj2 + * @return {object} + */ +function objDiff(obj1, obj2) { + if (obj1 === obj2) { + return {}; + } + + if ( + obj1 === null || obj2 === null + || typeof obj1 !== 'object' || typeof obj2 !== 'object' + || Array.isArray(obj1) !== Array.isArray(obj2) + ) { + return [obj1, obj2]; + } + + let result = {}; + for (let key in obj1) { + if (key in obj2) { + let diff = objDiff(obj1[key], obj2[key]); + if (Object.keys(diff).length) { + result[key] = diff; + } + } + } + return result; +};