JavaScript function explanation line by line

I came across the following JavaScript snippet and would like to know what it does:

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('')
}

      

0


a source to share


3 answers


It looks like some kind of encryption / obfuscation. Not knowing what filpTable

looks so hard to tell.



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('')
}

      

+3


a source


It loops through the string from the first character to the last, keeping the character found at each index in the array. For each character, if the "flipTable" array has an associated entry, it uses the flipTable entry rather than the character. The resulting array is then concatenated with '' to create a string.



In simpler terms, it changes the string while simultaneously changing every character that is the key for the flipTable for its associated record. Why would you do this I have no idea without context.

+3


a source


Similar to a simple encryption replacement . flipTable

contains the replacement alphabet, and the function executes each character in the string and replaces it with its own instance from that alphabet.

+1


a source







All Articles