2

Please help me simplifying this block of code.

any idea on how can I combine the last two if statements while preserving the functionality same.

Thanks.

document.addEventListener("keydown", function(e) { // shortcuts
  var mapping = {
    "noctrl9": function() { // tab
      var sStart = textarea.selectionStart,
        text = textarea.value;
      textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd);
      textarea.selectionEnd = sStart + 1;
    },
    66: function() { // B
      showHideStatusBar(statusBarOn ? false : true);
    },
    79: openDoc, // O
    82: newDoc, // R
    83: saveDoc, // S
    191: function() { // /
      alert("Welcome to " + appname + "!");
    }
  };
  if (e.ctrlKey && mapping[e.keyCode]) {
    e.preventDefault();
    mapping[e.keyCode]();
  }
  if (mapping["noctrl" + e.keyCode]) {
    e.preventDefault();
    mapping["noctrl" + e.keyCode]();
  }
});
1
  • pretty simple, just change your mapping to always include the value of e.ctrlKey ... mapping[e.ctrlKey +":"+e.keycode] Commented Nov 10, 2013 at 19:49

1 Answer 1

2

You could save the result of the logic in a variable, and then check separately.

var fn = e.ctrlKey && mapping[e.keyCode] || mapping['noctrl' + e.keyCode];
if (fn) {
  e.preventDefault();
  fn();
}

The assignment is equivalent to:

var fn;
if (e.ctrlKey && mapping[e.keyCode])
  fn = mapping[e.keyCode];
else
  fn = mapping['noctrl' + e.keyCode];

Or, a little shorter:

var fn = e.ctrlKey ? mapping[e.keyCode] : mapping['noctrl' + e.keyCode];

Or, while we're having fun with variations, this is a little more DRY:

var fn = mapping[(e.ctrlKey ? "" : "noctrl") + e.keyCode];

Note that the second if test could also be rewritten:

fn && (e.preventDefault(), fn());

That's a little too terse for me however.

Sign up to request clarification or add additional context in comments.

5 Comments

It won't work, as fn would not contain a function anymore but a boolean.
@BaliBalo I'm afraid it will work, as the JavaScript && and || operators don't work the way you think they do!
@BaliBalo try this: var f = true && function() { alert("Hi!"); }; f();
you're right, sorry. I didn't check it and forgot this behaviour. It would be clearer with var fn = e.ctrlKey ? mapping[e.keyCode] : mapping['noctrl' + e.keyCode]; though.
@user2965293 you'd need the second if statement, as in the code in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.