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.
source
share