1

I have the following code:

!function($){

    $.keys = {
        backspace: 8,
        tab: 9,
        enter: 13,
        escape: 27,
        space: 32,
        pageUp: 33,
        pageDown: 34,
        end: 35,
        home: 36,
        left: 37,
        up: 38,
        right: 39,
        down: 40,
        delete: 46,
        numpadEnter: 108,
        comma: 188
    };

}(window.jQuery);

And I want to build a function that returns a string of a key code for example:

$.keys.toString = function(key){
  switch(key){
    case $.keys.backspace:
      return 'backspace';
  }
};

The list would ofcourse be bigger, and support all the keys of the $.keys object. But is there a possibility that the $.keys.toString function actually uses the $.keys array to convert the int to string, so I don't have to make a switch statement.

Something like getKeyFromObjectValue?

Thanks for help :)

2 Answers 2

5

Since the list of keys is constant, you could simply create another list by iterating and reversing:

$.keysReversed = {};
$.each($.keys, function(key, value) {
  $.keysReversed[value] = key;  // value as key, key as value
});

Now, $.keysReversed contains of number/name pairs. This is faster than doing magic each time you call .toString - you can just return $.keysReversed[key].

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

Comments

1
$.keys.toString = function(key){
    $.each($.keys, function(key, value){
        if(value === key){
            return key;
        }
    });
};

Thanks for help :)

1 Comment

Returning in $.each doesn't have toString return something.

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.