JavaScript: creare un cookie con una funzione di utility

JavaScript: creare un cookie con una funzione di utility

Possiamo semplificare la creazione di un cookie in JavaScript implementando una funzione di utility.

Possiamo implementare la seguente funzione:


'use strict';

const setCookie = ({ name, path, expires }) => {

	if(!/^\d+(m|h|d)$/.test(expires)) {
        return false;
    }
    const parts = expires.split(/\d+/);
    const baseExpiresValue = parseInt(parts[0], 10);
    const baseExpiresUnit = parts[1];
    const ms = 1000;

    let duration = 0;

    switch(baseExpiresUnit) {
        case 'm':
            duration = baseExpiresValue * 60 * ms;
            break;
        case 'h':
            duration = baseExpiresValue * 60 * 60 * ms;
            break;
        case 'd':
            duration = baseExpiresValue * 60 * 60 * 24 * ms;
            break;
        default:
            duration = baseExpiresValue * 60 * ms;
            break;           
    }

    const now = new Date();
    let time = now.getTime();
    time += duration;

    now.setTime(time);

    const cookie = `${name}; expires=${now.toGMTString()}; path=${path}`;
    document.cookie = cookie;

    return true;

}

Esempio d'uso:


setCookie({
    name: 'test=test',
    expires: '1d',
    path: '/'
});

Torna su