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?
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...
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.
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.
The time complexity of the filter function is O(n) as well. At this moment, the total time complexity is O(2n).
Spec describes this function as linear search. Array.prototype.includes
Let O be ? ToObject(this value).
Let len be ? ToLength(? Get(O, "length")).
- If len is 0, return false.
- Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.)
- If n ≥ 0, then Let k be n.
- Else n < 0, Let k be len + n. If k < 0, let k be 0.
- 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With