understanding modenizer contains Function

44 views Asked by At

i was just going through the code of modenizer and came across the following function :

function contains(str, substr) {
    return !!~('' + str).indexOf(substr);
}

modenizer has alot of such small function for small tests. now coming to my question , i do understand that double equal is for converting everything to boolean value , but what is !!~ for also what is the

''  

before the str for ??

i have seen a few questions on SO that address similar issues but not exactly this issue , can somebody explain whats happening inside this function in the context of this example.

2

There are 2 answers

3
Tushar On BEST ANSWER

!!~('' + str)

  1. !!: Converts to boolean(true/false)
  2. ~: Bitwise NOT Unary operator operates by reversing all the bits in the operand. Inverts the bits of its operand.

    Bitwise NOTing any number x yields -(x + 1).

  3. '' + str: Type Casting Converts str to string

The operator first casts str to string then reverses the all the bits of binary and then returns the boolean result.

EXAMPLE

contains('abcd', 'd');

1. If str is not string then it is converted to string

    true + '' // "true"
    1 + ''    // "1"

2. `indexOf`
    The index of `substr` is returned.

3. `~`
    The bitwise NOT of 3 which is -(3 + 1) = -4

4. `!!`
    !!-4 = true


true will be returned.
0
Dmitry Poroh On

Nice thing. ~x is bitwise not. For -1 bitwise not is 0. So !!~ means 'is not -1' in boolean representation.