Posts Tagged ‘Random’
Posted in 'Code Snippets, JavaScript' by James on August 31st, 2009
Here’s a nifty little trick that allows you to write “contextual” JavaScript. It’s incredibly obtrusive and probably shouldn’t be used at all but it’s still a pretty cool idea:
<div id="some-div">
<script type=":contextual">
alert(this.id); // "some-div" is alerted
</script>
</div>
Instead of the this keyword referencing the global object (window) we can make it reference the parentNode of the script element. Here’s the code that makes it work:
(function(){
var scripts = document.getElementsByTagName('script'),
script, i = 0;
while ( (script = scripts[i++]) ) {
if ( /:contextual$/.test(script.type) ) {
(new Function(script.innerHTML)).call(script.parentNode);
}
}
})();
Take it or leave it! – I’m indifferent either way – yes, it’s obtrusive but you’ve got to admit, contextual JavaScript looks pretty neat!
Posted in 'Code Snippets, JavaScript' by James on February 14th, 2009
Getting a random (or rather, "pseudorandom") number in JavaScript is quite simple. Calling Math.random() usually gets the job done, but, in some instances you only want a random number to be returned if it hasn’t already been.
For such instances I’ve created a simple function which accepts an array as it’s first parameter. Calling the ‘getItem’ method retrieves a unique random item from the array:
The code:
// @param list: an Array
// @param alias: name for getter function,
// by default it's "getItem"
function RandomList(list, alias) {
if (!list) { return; }
var length = list.length;
this.indexes = [];
this.remainingItems = function(){
return this.indexes.length;
};
this[alias || 'getItem'] = function(){
var rand = Math.floor(Math.random() * this.indexes.length),
item = list[this.indexes[rand]];
this.indexes.splice(rand, 1);
return item;
};
while (length--) {
this.indexes[this.indexes.length] = length;
}
}
The second parameter is optional, it let’s you define a custom alias for the main getter function which, by default, is named ‘getItem’.
Usage:
// List of fruit:
var fruits = [
'Apple',
'Banana',
'Orange',
'Melon',
'Grape',
'Pear'
];
// Construct a new random list:
var myFruitBasket = new RandomList(fruits);
// Retrieve items (randomly):
/* 1: */ myFruitBasket.getItem(); // => 'Banana'
/* 2: */ myFruitBasket.getItem(); // => 'Apple'
/* 3: */ myFruitBasket.getItem(); // => 'Grape'
/* 4: */ myFruitBasket.getItem(); // => 'Orange'
/* 5: */ myFruitBasket.getItem(); // => 'Pear'
/* 6: */ myFruitBasket.getItem(); // => 'Melon'
/* 7: */ myFruitBasket.getItem(); // => UNDEFINED
// Last item is UNDEFINED because there are no fruit
// left in the basket!!!
As you can see, the function will only return unique random items (never the same one twice).
Another example:
// Every time the button is clicked
// get an item from the fruit basket
// and report how many are left:
var button = document.getElementById('the_button'),
// Custom alias ('getFruit'):
basket = new RandomList(fruits, 'getFruit');
button.onclick = function() {
if (!basket.remainingItems()) {
alert('None left!');
} else {
alert( basket.getFruit() ); // < We're using the new alias!
alert( 'Only ' + basket.remainingItems() + ' left in the basket!');
}
}
Be careful when using it with sparse arrays (e.g. [1,2,null,null,3,null,4]) because it will be difficult to detect when there are no items remaining.
Posted in 'Cool Stuff, JavaScript' by James on January 16th, 2009
Apparently it started back in 2003 but it only came to my attention about two years after that. It’s since been labelled as an internet meme which is interesting because the first time I saw it was on a poster at a train station near London, not on the internet! If you’re wondering what "it" is here you go:
Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn’t mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe.
Assuming you have no reading impairment understanding the above block of text is supposed to be easy, in fact most people (apparently) don’t notice that it’s jumbled until half way through. Here’s the un-jumbled version:
According to a researcher at Cambridge University, it doesn’t matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.
According to Matt Davis, who works at the Cognition and Brain Sciences Unit in Cambridge no such study (to his knowledge) has ever taken place. See his article which covers it all here: http://www.mrc-cbu.cam.ac.uk/~mattd/Cmabrigde/
Anyway, to test this ‘myth’ for myself I wanted to experiment with some more realistic everyday sentences, but me, being so lazy could not be bothered to manually jumble up letters so I did a google search for a ‘word jumbler’ and ‘letter jumbler’. Neither search gave me what I was after so I decided to create a little JavaScript ‘program’ to do it for me.
Posted in 'JavaScript' by James on November 17th, 2008
I thought it would be fun to do something like this a while ago but never bothered. I had a bit of spare time today so I made myself a little random word generator. Here it is:
function createRandomWord(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
alert( createRandomWord(10) );
It will alternate between consonants and vowels until it meets the specified length and then it will return a random word.
E.g.
- Fanewera
- Wifuwehi
- Feranuro
- Ponosive
- Boviredo
- Ravipare
- Nujaruki
They’re kinda silly but actually a couple of them might make good company names, actually "Boviredo" sounds a bit like an Italian pasta dish!
See a demo of it here: demo/random-word
Anyway, it was just a bit of fun, nothing serious! Please note that it doesn’t create real words, just random combinations of letters, obviously it could create a real word (since it’s random) but don’t expect it to.