Created
July 1, 2019 11:17
-
-
Save joeydebreuk/16ddad81112cf284168d99186aca5e69 to your computer and use it in GitHub Desktop.
Get item from list based on any String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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