Usa los helpers integrados de string, number, date y array
Total.js añade un conjunto de métodos a los tipos integrados de JavaScript. Están disponibles en toda la aplicación, así que conviene conocerlos antes de escribir un helper propio. Los de abajo están ejercitados por el ejemplo.
String: slug([max]) crea un texto apto para URL (minúsculas, sin acentos ni símbolos); format(a, b) sustituye {0}, {1}; encode() / decode() escapan y restauran HTML; padLeft(length, char) / padRight(); parseInt2() y parseFloat2() leen un número de un texto y devuelven 0 si no hay ninguno; isEmail(), isURL() y isJSON() validan; parseJSON() interpreta JSON y devuelve null si hay un error; md5(), sha1() y sha256() devuelven hashes hexadecimales; capitalize() pone en mayúscula la primera letra de cada palabra.
Number: format(decimals, thousands, decimal), por ejemplo (1234567.891).format(2) da 1 234 567.89.
Date: format('yyyy-MM-dd HH:mm'), add('1 day') y diff(date, 'days').
Array: take(n) y skip(n), first() y last(), trim() (recorta los textos y elimina los vacíos), findItem(field, value) y findIndex(field, value), remove(value) (elimina todas las coincidencias y devuelve el array), group(field) (devuelve [{ name, items }]) y quicksort(field).
Objetos: U.extend(target, source) mezcla source en target y lo devuelve; U.clone(object) hace una copia profunda.
exports.install = function() {
ROUTE('GET /utils/', utils);
};
function utils($) {
var items = [{ type: 'a', n: 1 }, { type: 'b', n: 2 }, { type: 'a', n: 3 }];
var original = { a: { b: 1 } };
var copy = U.clone(original);
copy.a.b = 2;
$.json({
slug: 'Hello Wörld & Co!'.slug(),
slugmax: 'Hello brave new world'.slug(11),
format: '{0} has {1} items'.format('Ann', 3),
encode: '<a href="x">&</a>'.encode(),
decode: '<b>'.decode(),
pad: ['7'.padLeft(3, '0'), '7'.padRight(3, '0')],
numbers: ['abc12x'.parseInt2(), '3,5kg'.parseFloat2(), 'none'.parseInt2()],
is: ['a@b.cz'.isEmail(), 'nope'.isEmail(), 'https://totaljs.com'.isURL(), '{"a":1}'.isJSON(), 'abc'.isJSON()],
json: ['{"a":1}'.parseJSON(), 'not json'.parseJSON()],
md5: 'abc'.md5(),
sha1: 'abc'.sha1(),
capitalize: 'hello big world'.capitalize(),
number: [(1234567.891).format(2), (1234567.891).format(2, ' ', ',')],
date: [new Date(2026, 0, 5, 9, 7).format('yyyy-MM-dd HH:mm'), new Date(2026, 0, 31).add('1 day').format('yyyy-MM-dd'), new Date(2026, 0, 5).diff(new Date(2026, 0, 1), 'days')],
take: [[1, 2, 3, 4, 5].take(2), [1, 2, 3, 4, 5].skip(3), [1, 2, 3].first(), [1, 2, 3].last()],
trim: ['a', '', ' b '].trim(),
find: [[{ id: 1 }, { id: 2 }].findItem('id', 2), [{ id: 1 }, { id: 2 }].findIndex('id', 2)],
remove: [1, 2, 3, 2].remove(2),
group: items.group('type'),
sort: [{ n: 'b' }, { n: 'a' }].quicksort('n'),
extend: U.extend({ a: 1 }, { b: 2 }),
clone: [original.a.b, copy.a.b]
});
}