Spanish Total.js
English
Documentation For AI agents
Contents

Prototypes

Methods that Total.js adds to String, Number, Date and Array: formatting, parsing, validation, hashing, dates and array helpers.

.md GitHub
On this page

Total.js 5 adds a set of methods to the built-in prototypes of JavaScript: String, Number, Date and Array. They are available in every file of the application (controllers, actions, schemas, definitions, views) as soon as the framework is loaded; you do not import anything.

var title = 'Hello World!';
title.slug();                     // hello-world
'{0} items'.format(5);            // 5 items
(1234.5).format(2);               // 1 234.50
new Date().add('1 day').format('yyyy-MM-dd');
users.findItem('id', 5);

The full list with every argument is in the reference Prototypes. This guide shows the groups and the methods you use most.

Strings: templates and text

format() fills numbered placeholders and args() fills named ones. args() can encode the values for HTML, JSON or URLs:

'Hello {0}, you have {1} messages.'.format('Peter', 5);

var tpl = '<a href="/docs/users/{id}/">{name}</a>';
tpl.args({ id: 10, name: '<Peter>' }, 'html');
// <a href="/docs/users/10/"><Peter></a>

For text from users and for URLs:

'Čaute, svet!'.slug();          // caute-svet
'<b>Hi</b>'.encode();           // <b>Hi</b>
'<b>'.decode();           // <b>
'<p>Hi</p>'.removeTags();       // Hi
'A long description'.max(10);   // A long ...
'hello world'.capitalize();     // Hello World
'Čučoriedka'.toASCII();         // Cucoriedka

toKeywords() and toSearch() prepare text for a simple full-text search: they lowercase it, remove diacritics and symbols, and make the matching tolerant (y and i are the same).

Strings: parsing

The parse* methods do not throw for bad input: they return a default value, undefined or an invalid date instead. Only parseConfig() throws for a value that cannot be evaluated when you do not pass onerr. This makes them safe for query strings and request bodies.

'10'.parseInt();                 // 10
'abc'.parseInt(1);               // 1 (the default)
'1,5'.parseFloat();              // 1.5
'on'.parseBoolean();             // true
'{"a":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON
'2024-05-01 12:30'.parseDate();  // a Date in UTC
'01/05/2024'.parseDate('dd/MM/yyyy');
'5 minutes'.parseDateExpiration(); // now + 5 minutes

Structured text formats have their own parsers:

'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }
'PORT=8000\nNAME="App"'.parseEnv();    // { PORT: '8000', NAME: 'App' }
'count (number) : 10'.parseConfig();   // { count: 10 }
'a,b\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]
req.headers['user-agent'].parseUA();   // Windows Chrome

parseContext() reads text made of blocks. Each block has header lines between two lines of at least 20 dashes and a body after them; the result is an array of objects with the header keys (lowercased) and body:

var text = PATH.root('prompts.txt');
var blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();
// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]

parseCSV() names the columns by letters (a, b, c, ...), so a file with a header line returns the header as the first object. Read the header, then map the letters to your names:

var rows = text.parseCSV(';');
var header = rows.shift();
var users = rows.map(row => ({ name: row.a, email: row.b }));

Strings: validation

The is* methods return a boolean. isEmail(), isPhone(), isURL(), isXSS() and isSQLInjection() use regular expressions stored in DEF.validators, so you can replace one of them at startup when your rules are different:

'info@example.com'.isEmail();     // true
'+421903123456'.isPhone();        // true
'https://totaljs.com'.isURL();    // true
UID().isUID();                    // true (the checksum is checked too)
'123'.isNumber();                 // true
'<script>'.isXSS();               // true

// /definitions/validators.js
DEF.validators.phone = /^\+?[0-9\s]{6,20}$/;

Strings: hashing and encryption

'text'.hash();               // a fast 32-bit number, for cache keys
'text'.hash('sha256');       // the same as 'text'.sha256()
'text'.md5();
'password'.sha512(CONF.secret);

var link = '123'.sign('key');    // 123-nzo165
link.sign('key', true);          // 123, or null when the text was changed

var secret = 'user@example.com'.encrypt('key');
secret.decrypt('key');           // user@example.com

var token = '123'.encrypt_uid(); // a short token for public URLs
token.decrypt_uid();             // 123

encrypt(), decrypt(), encrypt_uid() and decrypt_uid() use the secret configuration key when you do not pass a secret, so all instances of an application with the same configuration can read each other's values.

Numbers

(1234567.891).format(2);              // 1 234 567.89
(1234.5).format(2, ',', '.');         // 1,234.50
(1.005).round(2);                     // 1.01
(100).VAT(20);                        // 120
(100).discount(15);                   // 85
(5).padLeft(3);                       // 005
(1536000).filesize();                 // 1.46 MB
(3).pluralize('no files', '# file', '# files', '# files'); // 3 files
(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium

format() cuts extra decimals instead of rounding them: round first with round() when it matters, for example for prices. currency() formats an amount with a function you register in DEF.currencies.

Dates

The application runs in UTC unless the $timezone configuration key says otherwise, so dates are formatted in UTC by default.

var now = new Date();
now.add('1 day');                    // a new Date, now is not changed
now.add('-30 minutes');
now.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30
now.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024
now.format();                        // ISO string in UTC
now.extend('08:00');                 // the same day at 08:00
now.diff(created, 'days');           // days between created and now
now.setTimeZone('America/New_York').format('HH:mm'); // the time in New York

Arrays

The find methods accept a function, a property name with a value, or a single value:

var users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];

users.findItem('id', 2);              // { id: 2, ... } or null
users.findAll('role', 'admin');       // an array
users.findIndex(u => u.name === 'Anna'); // 1
users.findValue('id', 1, 'name');     // Peter
users = users.remove('id', 1);        // a new array without the item

users.quicksort('name');              // in place, by name
users.quicksort('role,name_desc');    // several columns
users.group('role');                  // [{ name: 'admin', items: [...] }, ...]
all.skip(20).take(10);                // paging

remove(), findAll(), take() and skip() return new arrays; quicksort() and random() change the array itself.

For asynchronous work over items, wait() calls a function for each item and waits for next(). The third argument runs several items at the same time:

files.wait(function(file, next) {
    FUNC.process(file, next);
}, function() {
    console.log('All files are processed');
}, 3);

async() runs an array of functions in sequence and limit() processes an array in chunks, which is handy for inserting many rows in batches.

Made in Europe