Skip to content

Instantly share code, notes, and snippets.

@andrewn
Created October 1, 2010 16:40
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 andrewn/606458 to your computer and use it in GitHub Desktop.
Save andrewn/606458 to your computer and use it in GitHub Desktop.
var Hash = {
/**
* Constant: URL_HASH_FACTOR
* {Float} Used to hash URL param strings for multi-WMS server selection.
* Set to the Golden Ratio per Knuth's recommendation.
*/
URL_HASH_FACTOR: (Math.sqrt(5) - 1) / 2,
/**
* Method: selectUrl
* selectUrl() implements the standard floating-point multiplicative
* hash function described by Knuth, and hashes the contents of the
* given param string into a float between 0 and 1. This float is then
* scaled to the size of the provided urls array, and used to select
* a URL.
*
* Parameters:
* paramString - {String}
* urls - {Array(String)}
*
* Returns:
* {String} An entry from the urls array, deterministically selected based
* on the paramString.
*/
selectUrl: function(paramString, urls) {
var product = 1;
for (var i=0, len=paramString.length; i<len; i++) {
product *= paramString.charCodeAt(i) * this.URL_HASH_FACTOR;
product -= Math.floor(product);
}
return urls[Math.floor(product * urls.length)];
}
};
var urls = [
"http://tile1.bbc.co.uk/tilechef/{recipeKey}/uk/unknown/composite/201010011500/{sourceKey}.png",
"http://tile2.bbc.co.uk/tilechef/{recipeKey}/uk/unknown/composite/201010011500/{sourceKey}.png",
"http://tile3.bbc.co.uk/tilechef/{recipeKey}/uk/unknown/composite/201010011500/{sourceKey}.png",
"http://tile4.bbc.co.uk/tilechef/{recipeKey}/uk/unknown/composite/201010011500/{sourceKey}.png"
];
var quadKeys = [ 031311121, 031311120, 031311122, 031311123, 031311132, 031311130, 031311112, 031311103, 031311102 ];
var recipeKeys = [ 21, 20, 22, 23, 32, 30, 12, 03, 02 ];
var sourceKeys = [ 0313111, 0313111, 0313111, 0313111, 0313111, 0313111, 0313111, 0313111, 0313111 ];
quadKeys.forEach( function ( item, index ) {
console.log( item, Hash.selectUrl( item + '', urls ) );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment