Saturday, February 5, 2011

Javascript Help

Hi i would simply like to know what this means:

function flipString(aString) {
 var last = aString.length - 1;
 var result = new Array(aString.length)
 for (var i = last; i >= 0; --i) {
  var c = aString.charAt(i)
  var r = flipTable[c]
  result[last - i] = r != undefined ? r : c
 }
 return result.join('')
}
  • It looks like some sort of encryption / obfuscation. Without knowing what filpTable looks like it's hard to say.

    function flipString(aString) {
     var last = aString.length - 1;
    
     // Create a new array with the length of the string
     var result = new Array(aString.length)
    
     // Walk through the string backwards
     for (var i = last; i >= 0; --i) {
      // Get the current character
      var c = aString.charAt(i)
    
      // Find the associated character in the flipTable
      var r = flipTable[c]
    
      // If the character wasn't in the flip table, use it as-is, else use the one we found
      // Store as (last-i) instead of (i) so it comes out backwards
      result[last - i] = r != undefined ? r : c
     }
    
     // Return the result as a string instead of an array
     return result.join('')
    }
    
    ceejayoz : Not sure why this was downvoted. Back up you go...
    DotSlashSlash : thanks.. so: var r = flipTable[c] is putting the object associated with a key ((which is in an array) which is the same as the character) in a variable?
    From Greg
  • It walks through a string from the first character to the last, whilst storing the character found at each index in an array. For each character, if the array "flipTable" has an entry associated with it, it uses the flipTable entry rather than the character. The resultant array is then joined with '' to make a string.

    In simpler terms, it reverses a string whilst simultaneously changing every character that is a key for flipTable to the entry associated with it. Why you'd do this, I have no idea without context.

  • Looks like a simple substitution cipher implementation. flipTable contains the substitution alphabet, and the function steps through each character in the string and replaces it with its counterpart from that alphabet.

    From ceejayoz

0 comments:

Post a Comment