21 ms·
~x.indexOf(…) would be “starts with” rather than “contains”, for negative numbers such as -2 (from ~1) are truthy.
by chrismorgan 12y ago
~x.indexOf(…) would be “starts with” rather than “contains”, for negative numbers such as -2 (from ~1) are truthy.
- nmjohn 12y ago> ~x.indexOf(…) would be “starts with” rather than “contains”, for negative numbers such as -2 (from ~1) are truthy. Nope, here's an example you can run it run in your console: function contains(needle, haystack) { return Boolean(~haystack.indexOf(needle)); } var haystack = "The quick brown fox jumps over the lazy dog"; console.log(contains("The", haystack)); console.log(contains("dog", haystack)); console.log(contains("brown fox jumps", haystack)); Here are three potential cases: haystack.indexOf('dog') = 40 -> truthy ~40 = -41 -> truthy haystack.indexOf('The') = 0 -> falsey (WRONG) ~0 = -1 -> truthy (FIXED) haystack.indexOf('nope') = -1 -> truthy (WRONG) ~-1 = 0 -> falsey (FIXED)
- Igglyboo 12y agoindexOf will only return -1, 0, or a positive integer