Javascript : utilities

Third article in my javascript journey and after fundamentals and arrays, here are some useful built-in types/functions that could be handy when writing a program. As usual, this is a non-verbose, developer-oriented article.

Set

A set cannot have duplicate elements.

let set = new Set([0, 1, 2, 3])
set.add(3); // ignored
set.add(4); // 4 added
let values = set.values(); // prints [0, 1, 2, 3, 4]
// Iterate
set.forEach(function(i) {
    console.log(i); // print each element
});

Map (i.e. dictionary)

Key/value pairs.

let map = new Map([
    ['Ben', 45],
    ['Jack', 96],
    ['Jody', '1'],
    ])
// Length
console.log(map.size);
// Get 1 entry
let weight = map.get('Ben'); // weight = 45
// Get all entries
let weights = map.entries(); // [['Ben', 45], ['Jack', 96], ...]
// add element
map.set('Johny', 47);
// edit element
map.set('Johny', 44);
// check existence of key
console.log(map.has('Max')); // prints false
// delete element
map.delete('Johny'); // no more 'Johny' entry
// iterate
map.forEach(function(key, value) => { ... });
// or
for(const [key, value] of map.entries()) {}
// or only keys
for(const key of map.keys()) {}

Date

let now = new Date();
// Specific date / time
//   Date(year, month, day, hour, minute, second)
let historicDate = new Date(45, 05, 16, 11, 00, 30);
// Specific date / time from milliseconds
//   Date(milliseconds) --> single param constructor expectes ms, not years
let datetime = new Date(123549876543543);
// From date string
let parsedString = new Date("2023-05-65");
// Format date
now.toDateString(); // redable format
now.toUTCString(); // UTC standard format
now.toISOString(); // ISO standard format

Math

Static mathematical library.

let x = 3.25879;
console.log(Math.PI);
Math.round(x); // round to nearest integer (4)
Math.ceil(x); // round up to integer (4)
Math.floor(x); // round down to integer (3)
Math.trunc(x); // retain integer part only (3)

JSON

JSON is a static class that is very useful to serialize classes to json format or deserialize the other way around.

// const will be an object containing all the json properties
const object = JSON.parse(text);
// serialize object
const string = JSON.stringify(object);

setTimeout / setInterval

// do() will be called in 3 sec
let myTimeout = setTimeout(do, 3000);
// Cancel timeout
clearTimeout(myTimeout);

// do() will be called every 4 sec
let myInterval = setInterval(do, 4000);
clearInterval(myInterval);

function do() {
    console.log("Done");
}