Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of the includes method in JavaScript

I have an array that contains some hash values of certain strings, I don't want duplicate values in my array so I use if logic like this:

if(!arrayOfHash.includes(hash_value)){   arrayOfHash.push(hash_value);  } 

I want to know the complexity of the includes method in JavaScript. Is it a linear search function or is it a modified search function?

like image 932
Nirdesh Kumar Choudhary Avatar asked Feb 13 '18 06:02

Nirdesh Kumar Choudhary


People also ask

What is the time complexity of includes in JavaScript?

O(n), as I am sure you are aware, is linear time, and O(1) is constant time, and nowhere does Yury say that the search has O(1) time complexity...

What is the use of include method?

includes() method is used to know either a particular element is present in the array or not and accordingly, it returns true or false i.e, if the element is present, then it returns true otherwise false.

Does set have O 1?

Yes. Time complexity of Set.has() is O(1) according to result of the test below. Helpful, I'm sure you're right, but best to make a test that runs for a significant period of time - IIRC, time units less than 10 milliseconds aren't extraordinarily trustworthy.

What is the time complexity of filter JavaScript?

The time complexity of the filter function is O(n) as well. At this moment, the total time complexity is O(2n).


1 Answers

Spec describes this function as linear search. Array.prototype.includes

  1. Let O be ? ToObject(this value).

  2. Let len be ? ToLength(? Get(O, "length")).

  3. If len is 0, return false.
  4. Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.)
  5. If n ≥ 0, then Let k be n.
  6. Else n < 0, Let k be len + n. If k < 0, let k be 0.
  7. Repeat, while k < len ... Increase k by 1.

Which is quite a reasonable choice in general case (list is not sorted, list is not uniform, you do not maintain additional datastructures along with the list itself).

like image 166
Yury Tarabanko Avatar answered Sep 18 '22 18:09

Yury Tarabanko