Prototypes
Methods that Total.js 4 adds to strings, numbers, dates and arrays.
Total.js 4 adds methods to the built-in prototypes of String, Number, Date and Array. They are available everywhere after the framework starts: in controllers, schemas, views, definitions and plugins. You call them on the value itself, so the code stays short.
var slug = model.name.slug();
var price = (model.price || 0).format(2);
var expire = NOW.add('1 month');
var user = users.findItem('id', id);The full list with every argument is in the reference of Prototypes.
Strings
Placeholders
String.format() replaces indexed placeholders and String.args() named ones. args() can encode the values for HTML, URL or JSON.
'{0} of {1}'.format(3, 10); // 3 of 10
'Hello {name}'.args({ name: 'Peter' }); // Hello Peter
'<a>{name}</a>'.args({ name: '<x>' }, 'html'); // <a><x></a>Converting values
Values from a query string or a form are strings. The parse* methods convert them and never throw:
| Method | Result |
|---|---|
'12'.parseInt() | 12 (0 or your default when the whole string is not a number) |
'Size 12px'.parseInt2() | 12 (the first number in the text) |
'12,5'.parseFloat() | 12.5 (a decimal comma is accepted) |
'on'.parseBoolean() | true for true, 1 and on |
'2024-01-15'.parseDate() | a Date |
'{"a":1}'.parseJSON() | an object, or undefined for invalid JSON |
function list() {
var page = (this.query.page || '').parseInt(1);
var limit = (this.query.limit || '').parseInt(20);
this.json({ page: page, limit: limit });
}Validation
String.isEmail(), String.isPhone() and String.isURL() use the regular expressions in DEF.validators, so you can change them in one place. String.isUID() checks the format and the checksum of an identifier created by UID().
function detail(id) {
if (!id.isUID()) {
this.throw404();
return;
}
// ...
}Text helpers
String.slug()makes a URL part from a title:'Hello World'.slug()giveshello-world.String.max(length)shortens a text and adds....String.capitalize()upper-cases the first letter of each word.String.toASCII()removes diacritics;String.removeTags()removes HTML tags.String.encode()andString.decode()convert HTML special characters.String.padLeft()andString.padRight()pad a string to a length.String.tslash()removes trailing slashes from a URL.
Hashes and encryption
String.md5(), String.sha1(), String.sha256() and String.sha512() return hex hashes; each accepts a salt. String.hash() selects the algorithm by name and without a name returns a fast number hash, good for cache keys.
String.encrypt(key) and String.decrypt(key) protect small values such as tokens. Decryption returns null when the key, the secret (CONF.secret) or the string does not match.
var token = JSON.stringify({ id: user.id }).encrypt('reset', true);
// later
var data = (this.query.token || '').decrypt('reset');
var obj = data ? data.parseJSON() : null;Search
String.keywords() returns the words of a text sorted by frequency and normalized for search. String.toSearch() normalizes a phrase in the same spirit. Store the keywords with the record and search by them.
item.search = (item.name + ' ' + item.description).keywords().join(' ');
var q = (this.query.q || '').toSearch();Markdown and JSON schemas
String.markdown() converts Markdown to HTML and String.toJSONSchema() turns an inline definition such as '*name:string(50), email:email' into a JSON schema object.
Numbers
Number.format() adds a thousands separator and decimals; Number.round() and Number.floor() work with decimals; Number.padLeft() adds leading zeros.
(1234567.891).format(2); // 1 234 567.89
(1234.5).format(2, '.'); // 1.234,50
(3.14159).round(2); // 3.14
(42).padLeft(6); // 000042Number.pluralize() picks a word form for 0, 1, 2-4 and other numbers, and replaces # with the number. The forms can also be one comma-separated string.
count.pluralize('no comments', '# comment', '# comments', '# comments');
count.pluralize('no comments,# comment,# comments,# comments');Prices have their own helpers: Number.VAT() adds or removes VAT, Number.discount() subtracts a percentage, and Number.add('+20%') applies an operation written as a string. Number.filesize() formats bytes as KB, MB and so on. Number.between() maps ranges to values.
Dates
Date.add() returns a new date moved by a period, and Date.format() writes the date with tokens such as yyyy, MM, dd, HH and mm.
var expire = NOW.add('7 days');
var label = NOW.format('dd.MM.yyyy HH:mm');
var left = expire.diff('hours');Date.diff() returns the difference in a unit, Date.extend('12:00') sets date or time parts, Date.toUTC() shifts the date by the timezone offset and Date.setTimeZone() converts it to an IANA timezone. Date.add() and Date.extend() never change the original date.
Arrays
Finding items
Array.findItem(), Array.findAll(), Array.findIndex() and Array.remove() accept either a function or a property name with a value:
var user = users.findItem('id', id);
var active = users.findAll('active', true);
var index = users.findIndex(item => item.email === email);
users = users.remove('id', id);Total.js replaces the native findIndex() to support this form. Some NPM modules replace it again, so the same method is also available as Array.TfindIndex().
Paging, sorting and lookups
var items = all.skip((page - 1) * limit).take(limit);
products.quicksort('price_desc');
var byid = users.toObject('id');Array.quicksort() sorts in place by one or more properties. Array.toObject() makes a lookup object, which is faster than repeated searches.
Asynchronous processing
Array.wait() calls an asynchronous function for each item, Array.async() runs a list of functions, and Array.limit() processes items in chunks. In each case you call next() to continue, and a final callback runs at the end.
users.wait(function(user, next) {
MAIL(user.email, 'News', '=mails/news', user, next);
}, function() {
console.log('Done');
});Number.async() does the same for a number of runs.