[removed] Quickly lookup value in object (like we can with properties)

后端 未结 4 515
名媛妹妹
名媛妹妹 2021-01-05 14:07

I have an object that has pairs of replacement values used for simple encoding / decoding (not for security, just for a convenience; too complicated to explain it all here).

相关标签:
4条回答
  • 2021-01-05 14:32

    It's more efficient to loop just once beforehand to create a reverse map:

    var str = "Hello World!",
        output = '',
        map = {
          "s":"d", "m":"e",
          "e":"h", "x":"l",
          "z":"o", "i":"r",
          "a":"w", "o":"!",
          "-":" "
        },
        reverseMap = {}
    
    for (j in map){
      if (!Object.prototype.hasOwnProperty.call(map, j)) continue
      reverseMap[map[j]] = j
    }
    
    output = str.replace(/./g, function(c){
      return reverseMap[c] || reverseMap[c.toLowerCase()].toUpperCase()
    })
    
    console.log(output)
    

    Instead of doing str.length * map.length, you'll do map.length + str.length operations.

    0 讨论(0)
  • 2021-01-05 14:32

    You can create a reversed version of the mapping programmatically (instead of by hand) and use it instead.

    var rev = {}
    for (key in obj)
        rev[obj[key]] = key
    
    0 讨论(0)
  • 2021-01-05 14:36

    A reverse encoder would make more sense, but you can write a replace function without all the hasOwnProperty etc.tests.

    var str= 'Hello World!',
    obj={
        's':'d',
        'm':'e',
        'e':'h',
        'x':'l',
        'z':'o',
        'i':'r',
        'a':'w',
        'o':'!',
        '-':' '
    }
    str= str.replace(/./g, function(w){
        for(var p in obj){
            if(obj[p]=== w) return p;
            if(obj[p]=== w.toLowerCase()) return p.toUpperCase();
        };
        return w;
    });
    

    returned value: (String) Emxxz-Azixso

    0 讨论(0)
  • 2021-01-05 14:46

    If you're looking for array keys check here.

    https://raw.github.com/kvz/phpjs/master/functions/array/array_keys.js

    function array_keys (input, search_value, argStrict) {
        var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = '';
    
        if (input && typeof input === 'object' && input.change_key_case) {
            return input.keys(search_value, argStrict);
        }
    
        for (key in input) {
            if (input.hasOwnProperty(key)) {
                include = true;
                if (search) {
                    if (strict && input[key] !== search_value) include = false;
                    else if (input[key] != search_value) include = false;
                }
                if (include) tmp_arr[tmp_arr.length] = key;
            }
        }
    
        return tmp_arr;
    }
    
    0 讨论(0)
提交回复
热议问题