Cakiety JavaScript razem razem


window.onload = () => {
    main()
}

let main = () => {
    let setName = document.querySelector('#setName')
    let setusername = document.querySelector('#setUsername')
    let getname = document.querySelector('#getname')
    let get_email = document.querySelector('#getUsername')

    //set name 
    setName.addEventListener('click', setnameFn('name', 'mohammed nazim', 2))

    //set userName 
    setusername.addEventListener('click', setnameFn('email', '[email protected]', 3))

    //get name
    getname.addEventListener('click', getnameFn('name'))

    //get email
    get_email.addEventListener('click', getnameFn('email'))
}


/**
 * set name function defined here
 */
let setnameFn = (cname, cValue, exdays) => {
    let expaired
    return () => {
        let date = new Date()
        date.setTime(date.getTime() + (exdays * 24 * 60 * 60 * 1000));
        expaired = expaired + date.toUTCString()

        document.cookie = cname + '=' + cValue + ';' + expaired + ";path=/"
    }
}

//['[email protected]', ' name=mohammed nazim']
let getnameFn = (cname) => {
    return () => {
        let getData = document.cookie.split(';')
        let nameLength = cname + '='

        for (let i = 0; i < getData.length; i++) {
            let usernames = getData[i]

            while (usernames.charAt(0) === ' ') {
                usernames = usernames.substring(1)
            }
            if (usernames.indexOf(nameLength) === 0) {
                alert(usernames.substring(nameLength.length))
            }

        }

        // the (return) will be execute if the (for loop) dosen't execute
        return ''
    }
}
Mohammad Nazim