开发者

Javascript arbitrary element of an array based on a "string" seed

I'm relatively new to javascript. I'm looking for a javascript function to get an arbitrary element of a given array based on a given string input.

A random(seed) function would be useful but I can't find one. Or maybe a way to xor hash the bytes in a string.

I can't use jquery, and I'm hoping for an answer that's relatively short.

Edit for examples:

var myArray = ["foo", "bar", "24", "asdf"];
开发者_如何学运维

the signature would look like

function ArbitraryElement(arr, seed)

and outputs would look something like:

ArbitraryElement(myArray, "what") // "foo"
ArbitraryElement(myArray, "that") // "24"
ArbitraryElement(myArray, "what") // "foo"
ArbitraryElement(myArray, "boo")  // "24"
ArbitraryElement(myArray, "cat")  // "asdf"
// etc...


You could sum the char codes with reduce, IE9 native and IE8 and below with shim included in link:

function ArbitraryElement(arr, seed) {
    seed = (seed || '') + "xx"; // ensure a seed that can be reduced
    var charCodes = seed.split('').reduce(function(a, b, i) {
        return (i == 1 ? a.charCodeAt(0) : +a) + b.charCodeAt(0);
    });
    return arr[charCodes % arr.length]
}

EDIT:

Here's an update: http://jsfiddle.net/sqA6Z/


I assume that you would like to have this "array lookup" be deterministic, in that passing in the same string would result in the same array index being accessed?

If so, I recommend performing a hash on the string, and then modding it by the size of the array.

You can use this to compute an MD5 hash

var foo = getHash(inputString);
var index = foo % myArray.length;


Here's a function return a random element from your array (no seed is needed):

function getRandomItem(input) {
    var index = Math.floor(Math.random() * input.length);
    return(input[index]);
}

var myArray = ["foo", "bar", "24", "asdf"];
getRandomItem(myArray);
getRandomItem(myArray);
getRandomItem(myArray);

Demo here: http://jsfiddle.net/jfriend00/J5QKE/


I like the accepted answer, although I prefer a simpler recursion alternative.

const charSum = (str) =>
!str.length ? 0 : str.charCodeAt(0) + charSum(str.substr(1));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜