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

后端 未结 4 517
名媛妹妹
名媛妹妹 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.

提交回复
热议问题