commit a8a00f0f490abdbe46e7a3265cabd3609957c6fb Author: AJ ONeal Date: Tue Dec 3 00:44:42 2013 -0700 initial commit diff --git a/example.js b/example.js new file mode 100644 index 0000000..aa5854f --- /dev/null +++ b/example.js @@ -0,0 +1,13 @@ +(function () { + 'use strict'; + + var shuffle = require('./').knuthShuffle + , a = [2,11,37,42] + , b + ; + + // The shuffle modifies the original array + // calling a.slice(0) creates a copy, which is assigned to b + b = shuffle(a.slice(0)); + console.log(b); +}()); diff --git a/index.js b/index.js new file mode 100644 index 0000000..d0cc5f6 --- /dev/null +++ b/index.js @@ -0,0 +1,29 @@ +/*jshint -W054 */ +(function (exports) { + 'use strict'; + + // http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array + function shuffle(array) { + var currentIndex = array.length + , temporaryValue + , randomIndex + ; + + // While there remain elements to shuffle... + while (0 !== currentIndex) { + + // Pick a remaining element... + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex -= 1; + + // And swap it with the current element. + temporaryValue = array[currentIndex]; + array[currentIndex] = array[randomIndex]; + array[randomIndex] = temporaryValue; + } + + return array; + } + + exports.knuthShuffle = shuffle; +}('undefined' !== typeof exports && exports || new Function('return this')())); diff --git a/package.json b/package.json new file mode 100644 index 0000000..7b2a0b3 --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "knuth-shuffle", + "version": "1.0.0", + "description": "The Fisher-Yates (aka Knuth) shuffle for Browser and Node.js", + "main": "index.js", + "scripts": { + "test": "node example.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/coolaj86/knuth-shuffle.git" + }, + "keywords": [ + "ronald", + "fisher", + "frank", + "yates", + "fisher-yates", + "donald", + "knuth", + "shuffle", + "random", + "randomize", + "unbiased", + "algorithm" + ], + "author": "AJ ONeal (http://coolaj86.info/)", + "license": "Apache2", + "bugs": { + "url": "https://github.com/coolaj86/knuth-shuffle/issues" + } +}