0

I need some help with my JS logic here. So basically I am getting a bunch of permissions and storing them as follows:

for( var i=0 ; i<permissions.length ; i++ ) {
    p[permissions[i].PERMISSION] = true;
}

The values of the permissions are as follows

p.SELECT_USER,

p.INSERT_USER,

p.UPDATE_USER, etc and so on

Now I want to display/hide a window based on the value of permissions. I need some logic help in my if condition So basically I want something like,

if( 'permissions beigns with the word SELECT' && 'permissions does not begin with any other word' ) {
    this.window.hide()
} else {
    this.window.show()
}

is there any efficient way I cant do this by modifying my for loop?

Micheal
  • 2,272
  • 10
  • 49
  • 93
  • 1
    So are you worried about the security implications of storing permissions in clear text? – Mike Robinson Jul 19 '12 at 21:18
  • 1
    "is there any efficient way" --- when person says that, it means that they **already have** working solution that is proven inefficient. Do you have any? – zerkms Jul 19 '12 at 21:19
  • I have about 50 permissions and I cannot include them one by one in a if condition , maybe efficient is a wrong word, shorter way would be the right one – Micheal Jul 19 '12 at 21:41
  • Could you please show us what that ominous `permissions` array contains? – Bergi Jul 19 '12 at 21:53

1 Answers1

1
if( /^SELECT/.test(/*some permissionvalue*/) ) { /*...*/ } 

would be pretty short and I suppose efficient enough?

Other idea (one liner replaces your code, if hide and show are existing methods contained by this.window):

this.window[ /^SELECT/.test(/*some permissionvalue*/) ? 'hide' : 'show' ]();

/^SELECT/.test(/*some permissionvalue*/) in both suggestion means: test if the given value starts with 'SELECT'. Like @Steve Wang noted, you could replace that using
/*some permission value*/.indexOf('SELECT') === 0 to be even more efficient.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    A slightly more efficient solution is to use String.prototype.indexOf, e.g.`str.indexOf("SELECT") == 0`, since regex usage is definitely overkill here. – Steve Wang Jul 19 '12 at 21:38
  • @SteveWang: Please read about [startsWith](http://stackoverflow.com/questions/646628/javascript-startswith). indexOf is much less efficient (even the regex is much faster)! – Bergi Jul 19 '12 at 21:55
  • startsWith isn't part of String.prototype, so it's not implemented natively. Also, considering the length of the strings, I'd imagine that indexOf won't be noticeably worse than substr or slice. – Steve Wang Jul 19 '12 at 21:59
  • For a naive test, see http://jsperf.com/string-startswith-implementations -- as always, it depends on the browser. – Steve Wang Jul 19 '12 at 22:09