When to use set in javaScript

I am just a beginner in javaScript and have a python background. I tried to complete this exercise to check if each character of line2 is in line1. For example, if string1 is "hello", I will return it trueif string2 is "leh" and falseif string2 is "low".

What I came up with:

function mutation(arr) {
  var set = new Set(string1.split(''));
  for (var i = 0; i < string2.length; i++)
    if (!set.has(string2[i]))
      return false;
  return true;
}

I could also go on converting string2 to a set and then make a difference, i.e. an operation set(string2) - set(string1)that will show me a set of characters that are on line2 but not on line1, but I read that creating a set is expensive so I did not go any further.

I checked the other solutions, and each used a method string1.indexOf(letter)to check if each letter in line2 in line string1 exists or not.

I want to know when to use the difference in settings. Why does everyone use a method array.indexOf()that costs O (n) instead of a method set.has()that is O (1). Are there any pitfalls if I use set.has(). (let's say browser compatibility)?

Any recommendation is helpful.

+4
source share
2 answers

MDN - . Set - Implementations .

, " ", element_of, add delete.

Array vs Set annwer .


, has , String indexOf ( includes), Set .

:

function existsSet(str1, str2) {
  const set = new Set(str1);
  return ![...str2].some(char => !set.has(char));
}

function existsString(str1, str2) {
  return ![...str2].some(char => !str1.includes(char));
}

1 , :

existsSet: 1.29s
existsString: 0.47s

, Set.


, JsFiddle:

https://jsfiddle.net/mspyratos/zwx3zcx1/11/

+4

. .has() , indexOf(), (: ).

indexOf() ( , ).

. , .

, , , .

+1

Source: https://habr.com/ru/post/1680837/


All Articles