Skip to content

Instantly share code, notes, and snippets.

@joeydebreuk
Created July 1, 2019 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeydebreuk/16ddad81112cf284168d99186aca5e69 to your computer and use it in GitHub Desktop.
Save joeydebreuk/16ddad81112cf284168d99186aca5e69 to your computer and use it in GitHub Desktop.
Get item from list based on any String
// Get item from list based on any String
// Example:
// var arr = [0, 1, 2, 3, 4, 5, 6];
// pickValueByString(arr, "Text"); // >> 1
// pickValueByString(arr, "text"); // >> 5
// pickValueByString(arr, "other text"); // >> 2
// pickValueByString(arr, "Text"); // >> 1
function byteValue(str) {
var totalBytes = 0;
var character;
var stack;
var i;
var stringLenght = str.length;
// From: https://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string
for (i = 0; i < stringLenght; i++ ) {
character = str.charCodeAt(i);
stack = [];
do {
stack.push( character & 0xFF ); // push byte to stack
character = character >> 8; // shift value down by 1 byte
}
while ( character );
totalBytes += +stack;
}
return totalBytes;
}
function pickEntryByString(array, string) {
var arrayLength = array.length;
var index = byteValue(string) % arrayLength;
return array[index];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment