From 9f873e5819b24432c7f98aa2fff8d61e1c3bb5a4 Mon Sep 17 00:00:00 2001 From: sricharankrishnan Date: Tue, 4 Jan 2022 16:34:02 +0530 Subject: [PATCH] [New Feature]: Suggestions - introduced 'Check Is Array' in the module.exports section to make sure that we receive an array - using pre built 'Array.forEach' to iterate over the first array - using pre build 'Array.findIndex' to fetch the index for the item to be check for in the diff array --- index.js | 69 +++++++++++++++++++++++++++----------------------------- 1 file changed, 33 insertions(+), 36 deletions(-) diff --git a/index.js b/index.js index 90f2807..80e1c2a 100644 --- a/index.js +++ b/index.js @@ -1,47 +1,44 @@ -/*! - * arr-diff - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - 'use strict'; -module.exports = function diff(arr/*, arrays*/) { - var len = arguments.length; - var idx = 0; - while (++idx < len) { - arr = diffArray(arr, arguments[idx]); - } - return arr; -}; - -function diffArray(one, two) { - if (!Array.isArray(two)) { - return one.slice(); +function performArrayDiff(arrayOne, arrayTwo) { + /* yes we need to make sure that the second argument in this is always an array */ + if (!Array.isArray(arrayTwo)) { + return arrayOne.slice(0); } + else { + /* take a clone so that you do not affect the original values */ + let sourceArray = arrayOne.slice(0); + let diffArray = arrayTwo.slice(0); - var tlen = two.length - var olen = one.length; - var idx = -1; - var arr = []; + let resultArray = []; - while (++idx < olen) { - var ele = one[idx]; + sourceArray.forEach((value) => { + let foundIndex = diffArray.findIndex((element) => { + return element === value; + }); - var hasEle = false; - for (var i = 0; i < tlen; i++) { - var val = two[i]; - - if (ele === val) { - hasEle = true; - break; + if (foundIndex === -1) { + resultArray.push(value); } - } + }); - if (hasEle === false) { - arr.push(ele); + return resultArray; + } +} + +module.exports = (array) { + if (!Array.isArray(array)) { + throw new Error("First Argument: 'array' needs to always be an array!"); + } + else { + let argsLength = arguments.length; + let index = 1; + + /* iteration */ + while (index < argsLength) { + array = performArrayDiff(array, arguments[index]); + ++index; } + return array; } - return arr; }