1

I want to make a single function that can handle ===, !== to sort elements. I have no idea how to do this.Please suggest how can i do this

HTML

 <div class="aa">1</div>
  <div class="aa">2</div>
  <div class="aa">3</div>
  <div class="aa">4</div>
  <div class="aa">2</div>
  <div class="aa">6</div>

$val=2;

function getVal(div,symbol){
  div.filter(function () {
              return parseInt($(this).html(), 10)===$val;  //i want to use passed symbol in place of ===     
            }).show();
}

getVal($('.aa'),'===')

Demo http://jsbin.com/EzEREFU/2/

Ace
  • 841
  • 9
  • 23

3 Answers3

3

Need to apply some cleverness ;)

function getVal(div,invert) {
    div.filter(function() {
        return (parseInt($(this).html(),10) === $val) ^ invert;
    }).show();
}

That ^ is an XOR operator. It's supposed to be bitwise, but it works on booleans just fine.

To use:

getVal($(".aa"),false); // "==="
getVal($(".aa"),true); // "!=="

If you want to be able to pass in "===" or "!==", try this:

function getVal(div,symbol) {
    var invert = symbol.charAt(0) != "=";
    div.filter(function() {
        return (parseInt($(this).html(),10) === $val) ^ invert;
    }).show();
}

Obligatory Vanilla JS solution:

function getVal(className,symbol) {
    [].forEach.call(document.getElementsByClassName(className),function(elm) {
        if( (parseInt(elm.firstChild.nodeValue,10) === $val) ^ invert)
            elm.style.display = "block";
    });
}
getVal("aa","==="); // show where equal
getVal("aa","!=="); // show where not equal

What's that? Older browsers? Psh, sod 'em. If people deliberately make our lives difficult by disabling Windows Update, they don't deserve our awesome websites.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You can not actually pass a string as an operator in javascript, unless you use eval(..) (which is typically not recommended). I'd suggest another option:

var equals = function(x,y) { return x === y; }
var notEquals = function(x,y) { return x !== y; }

Now,

function getVal(div,operation){
  div.filter(function () {
              return operation(parseInt($(this).html(), 10),$val);
            }).show();
}

getVal($('.aa'),equals); //equals defined above.

You can create custom functions like equals, notEquals, etc. Further, you can put them in a dictionary, and where keys are your "symbols", and the value is the function, and hence invoke it.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
1

you can try like this -

$val=2;


function getVal(div,symbol){
  div.filter(function () {
    if(symbol=='equalsTo')
      return parseInt($(this).html(), 10)===$val;
    else if(symbol=='notEqualsTo')
      return parseInt($(this).html(), 10)!==$val;
  }).show();
}

getVal($('.aa'), 'notEqualsTo'); //notEqualsTo or equalsTo

example - http://jsbin.com/EzEREFU/4/

HADI
  • 2,829
  • 1
  • 26
  • 26