From 18e56f1ed8359250b1dcd955ec0361062bcc08fd Mon Sep 17 00:00:00 2001 From: ricardodoberstein Date: Fri, 13 May 2022 19:33:29 -0300 Subject: [PATCH] Optimization of arrayUtils.js common function to use less memory and run faster --- utils/arrayUtils.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/utils/arrayUtils.js b/utils/arrayUtils.js index b59d48e3..44e2c329 100644 --- a/utils/arrayUtils.js +++ b/utils/arrayUtils.js @@ -6,10 +6,19 @@ function last(array) { return array[array.length - 1]; } -// return array of values common for both array a and array b +/** + * Return common elements between two arrays. + * @param {*} a array of any type. + * @param {*} b array of any type. + * @returns Array of common elements between A and B. + * @example + * const a = [1, 2, 3, 4]; + * const b = [1, 3, 6, 7]; + * const result = common(a, b); + * console.log(result); // => [1, 3]; + */ function common(a, b) { - const setB = new Set(b); - return [...new Set(a)].filter(a => setB.has(a)); + return a.filter(element => b.includes(element)); } function unique(array) {