🍦 Vanilla JavaScript

Projects for the Vanilla JS Academy

Day 23

Monster Shuffle

Goal

Shuffle and display an array of monsters.

Project

View Source
(() =>
{
	let monsters = [
		'monster1',
		'monster2',
		'monster3',
		'monster4',
		'monster5',
		'monster6',
		'monster7',
		'monster8',
		'monster9',
		'monster10',
		'monster11',
		'sock'
	];

	let elAppRow = document.querySelector( ".app-row" );

	/**
	 * Randomly shuffle an array
	 * https://stackoverflow.com/a/2450976/1293256
	 * @param  {Array} array The array to shuffle
	 * @return {String}      The first item in the shuffled array
	 */
	let shuffle = array =>
	{
		var currentIndex = array.length;
		var 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;
	};

	/**
	 * @param [array] monsters
	 */
	let render = monsters =>
	{
		let html = "";
		monsters.forEach( monster =>
		{
			console.log( monster );
			html += `<img src="/images/23/${monster}.svg" alt="${monster}">`;
		});

		elAppRow.innerHTML = html;
	}

	document.querySelector( "#shuffle-monsters" ).addEventListener( "click", e =>
	{
		shuffle( monsters );
		render( monsters );
	});

	shuffle( monsters );
	render( monsters );
})();