Skip to content

Instantly share code, notes, and snippets.

@franklinjavier
Created March 21, 2013 00:52
Show Gist options
  • Save franklinjavier/5209867 to your computer and use it in GitHub Desktop.
Save franklinjavier/5209867 to your computer and use it in GitHub Desktop.
Utils
var Infograph = window.Infograph || {};
(function( window, document, $ ) {
'use strict';
Infograph = {
Utils: {
/**
* Funcao que transforma a primeira letra de cada palavra em maiuscula,
* exceto as preposicoes de, do, da, dos e das.
*
* @param {string} str - String a ser transformada
* @example Infograph.Utils.capitalizeFirstLetter('JOAO DA SILVA') // Joao da Silva
*/
capitalizeFirstLetter: function( str ) {
str = str.toLowerCase();
var pieces = str.split(' '),
piece,
piecesLength = pieces.length,
firstLetter;
while ( piecesLength-- ) {
piece = pieces[ piecesLength ];
if (piece !== 'de' &&
piece !== 'do' &&
piece !== 'da' &&
piece !== 'dos' &&
piece !== 'das' ) {
firstLetter = piece.charAt(0).toUpperCase();
pieces[ piecesLength ] = firstLetter + piece.substr(1);
}
}
return pieces.join(' ');
},
/*
* Remove acentos e substitui espacos por hifen
*
* @param {string} str - String a ser alterada
* @example Infograph.Utils.toSlug('São Paulo'); // sao-paulo
*/
toSlug: function() {
var st = arguments[0].toLowerCase();
st = st.replace(/[\u00C0-\u00C5]/ig, 'a')
.replace(/[\u00C8-\u00CB]/ig, 'e')
.replace(/[\u00CC-\u00CF]/ig, 'i')
.replace(/[\u00D2-\u00D6]/ig, 'o')
.replace(/[\u00D9-\u00DC]/ig, 'u')
.replace(/[\u00D1]/ig, 'n')
.replace(/[^a-z0-9 ]+/gi, '')
.trim().replace(/ /g, '-')
.replace(/[\-]{2}/g, '');
return ( st.replace(/[^a-z\- ]*/gi, '') );
},
/*
* Remove acentos
*
* @param {string} str - String a ser alterada
* @example Infograph.Utils.removeAccent('São Paulo'); // Sao Paulo
*/
removeAccent: function() {
var st = arguments[0].toLowerCase();
st = st.replace(/[\u00C0-\u00C5]/ig, 'a')
.replace(/[\u00C8-\u00CB]/ig, 'e')
.replace(/[\u00CC-\u00CF]/ig, 'i')
.replace(/[\u00D2-\u00D6]/ig, 'o')
.replace(/[\u00D9-\u00DC]/ig, 'u')
.replace(/[\-]{2}/g, '');
return ( st.replace(/[^a-z\- ]*/gi, '') );
},
/*
* Requisicao em ajax do tipo jsonP
*
* @param {object} str - Objeto
*/
getData: function( options ) {
var data = {},
url = options.url,
dataId = options.id,
callback = options.callback,
jsonpCallback = options.jsonpCallback;
$.ajax({
url : url,
dataType : 'jsonp',
crossDomain : true,
jsonp : false,
jsonpCallback : jsonpCallback || 'jsonpCB',
cache : true,
success: function( result ) {
if ( !result )
return false;
if ( Object.typeOf(result) === 'string' )
result = $.parseJSON($.trim(result));
if ( dataId )
data[ dataId ] = result;
else
data = result;
callback.call(null, data);
}
});
},
/*
* Preload de imagens
*
* @param {array} imgs - Array com os paths das imagens
* @example Infograph.Utils.preload(['img/foto1.jpg', 'img/foto2.jpg']);
*/
preload: function( imgs ) {
for( var i in imgs ) {
(new Image()).src = imgs[i];
}
},
base64: {
encode: function( data ) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafał Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
},
decode: function ( data ) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['atob'] == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return dec;
}
}
}
};
/**
* Escapa a string.
*/
window._escape = function(str) {
return encodeURIComponent(_unescape(str));
}
/**
* Retorna a string no estado normal
*/
window._unescape = function(str) {
try {
return _cleanText(decodeURIComponent(unescape(str)));
}
catch(e) {
if(/URI malformed/.test(e))
return _cleanText(unescape(str));
return str;
}
}
/**
* Transforma o texto com html entities em texto puro
*/
window._cleanText = function(str) {
return str.replace(/&#(\d+);/g, function(str, code) { return String.fromCharCode(code) });
}
/**
* Verifica o tipo do objeto (typeof de verdade)
*
* @param {Object} O objeto a ser avaliado
* @returns {String} O tipo do objeto
*
* @examples:
* Object.typeOf([1,2,3]) // "array"
* Object.typeOf(/a-z/) // "regexp"
* Object.typeOf(window) // "global"
* Object.typeOf(JSON) // "json"
* Object.typeOf({}) // "object"
* (function() {console.log(Object.typeOf(arguments))})() // "arguments"
* Object.typeOf(new ReferenceError); // "error"
* Object.typeOf(new Date); // "date"
* Object.typeOf(Math); // "math"
* Object.typeOf(JSON); // "json"
* Object.typeOf(new Number(4)); // "number"
* Object.typeOf(new String("abc")); // "string"
* Object.typeOf(new Boolean(true)); // "boolean"
*/
Object.typeOf = (function( global ) {
return function( obj ) {
if ( obj === global ) {
return 'global';
}
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
})( this );
/*
* Retorna o tamanho de um Object ou Array
*
* @param {Object} O objeto a ser avaliado
* @returns {Number} O length do Object
*
* @examples:
* Object.size([1,2,3]) // 3
* Object.size({y: 0, x: 1}) // 2
*
*/
Object.size = function( obj ) {
var size = 0, key;
for ( key in obj ) {
if ( obj.hasOwnProperty( key ) )
size++;
}
return size;
};
/*
* Randomiza um array
*
* @param {Array} O array a ser randomizado
* @returns {Array} O array randomizado
*
* @examples:
* Array.shuffle([1,2,3]) // [2, 3, 1]
*
*/
Array.shuffle = function( array ) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};
if( !String.prototype.trim ) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
})( window, document, jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment