Jump to content

User:Gary/functions.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function addClass(element, className)
{
	classes = element.className.split(' ');
	classes.push(className);
	classes = classes.join(' ');
	element.className = classes;
}

function capitalize(string)
{
	return string.charAt(0).toUpperCase() + string.slice(1);
}

function convertTimestampToDate(timestamp)
{
	var matches = timestamp.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z/);
	
	var origToday = new Date();
	today = new Date(origToday.getFullYear(), origToday.getMonth(), origToday.getDate());
	var origThen = new Date();
	origThen.setUTCFullYear(matches[1]);
	origThen.setUTCMonth(matches[2] - 1);
	origThen.setUTCDate(matches[3]);
	origThen.setUTCHours(matches[4]);
	origThen.setUTCMinutes(matches[5]);
	origThen.setUTCSeconds(matches[6]);
	return origThen;
}

function convertToKB(bytes)
{
	return (bytes / 1024).toFixed(0) + ' kB';
}

function convertToOrdinal(number)
{
	mod = number % 10;
	
	switch (mod)
	{
		case 1: ordinal = 'st'; break;
		case 2: ordinal = 'nd'; break;
		case 3: ordinal = 'rd'; break;
		case 0:
		default: ordinal = 'th';
	}
	
	return number + ordinal;
}

function formatJSON(obj)
{
	if (!obj['query'] || !obj['query']['pages']) return false;
	
	var vars = [];
	vars['pages'] = obj['query']['pages'];
	vars['page'] = [];
	
	for (var i in vars['pages']) vars['page'].push(i);
	if (vars['page'].length != 1) return false;
	
	vars['page'] = obj['query']['pages'][vars['page'][0]];
	vars['pageName'] = vars['page']['title'].replace(/ /g, '_');
	
	if (vars['page']['revisions'])
	{
		vars['firstRevision'] = vars['page']['revisions'][0];
		vars['revisions'] = vars['page']['revisions'];
	}
	
	return vars;
}

function hasClass(element, className)
{
	if (!element || !element.className) return false;
	
	var classes = element.className.split(' ');
	for (var i = 0; i < classes.length; i++)
	{
		if (classes[i] == className)
			return true;
	}
	
	return false;
}

function isUnsafe()
{
	if (typeof(unsafeWindow) != 'undefined') return true;
	else return false;
}

function pluralize(word, count, plural)
{
	if (plural == null)
		plural = word + 's';

	return (count == 1 ? word : plural);
}

function trim(stringToTrim) 
{
	return stringToTrim.replace(/^\s+|\s+$/g, '');
}