Skip to content

Instantly share code, notes, and snippets.

@erhaem
Created October 25, 2024 03:24
Show Gist options
  • Select an option

  • Save erhaem/014fed182a99050c98ac1c953eeea234 to your computer and use it in GitHub Desktop.

Select an option

Save erhaem/014fed182a99050c98ac1c953eeea234 to your computer and use it in GitHub Desktop.
AingCreations Encoding. I miss AingCreations :'(

Encode/decode strings the AingCreations way. That is to map characters in a string to their respective indices and reconstructing the original string from that mapping

/**
 * @param {string} str - The string to encode.
 * @returns {object} - The object mapping each character to an array of its indices
 */
var encode = function(str) {
  var mapping = {};

  for (var i = 0; i < str.length; i++) {
    var char = str[i];

    if (!mapping[char]) {
      mapping[char] = [];
    }

    mapping[char].push(i);
  }

  return mapping;
};

/**
 * @param {object} mapping - The mapping of string characters
 * @returns {string} - The decoded string
 */
var decode = function(mapping) {
  var result = [];

  for (var char in mapping) {
    for (var i in mapping[char]) {
      var idx = mapping[char][i];
      result[idx] = char;
    }
  }

  return result.join("");
};

Example

var encoded = encode('aing'); 
console.log(JSON.stringify(encoded));
/** encoded: {"a":[0],"i":[1],"n":[2],"g":[3]} */

var decoded = decode(encoded);
console.log(decoded);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment