Simple unshift and unique not working in JavaScript

Very simplistic code, yet been frying my brain for a few hours? So as you can see on the add function, it basically takes 2 params; an IP Address & a UNIX date

const redis = require("redis"), client = redis.createClient();
const {promisify} = require('util');
const getAsync = promisify(client.get).bind(client);
const setAsync = promisify(client.set).bind(client);

_ = require('lodash');
_weg = require('wegweg')({
    globals: false
});

module.exports = {

    add: async function (ip, cday) {
        var key = _weg.md5('dact:' + ip);
        return await getAsync(key).then((result) => {
            let value;
            if (result == null) {
                value = [];
            } else {
                value = result;
            }
            value = value.unshift(cday);
            value = _.uniq(value);
            return setAsync(key, value);
        });
    }

};

So if I'm going ahead and passing both:

await ping_history.add("127.0.0.1", 1562774400);

It seems to not be inserting an array or something? key should be an MD5 & value should simply be an array of dates which are all unique.

1 answer

  • answered 2019-07-10 22:06 Barmar

    The unshift method modifies the array in place, it doesn't return a new array. The return value of unshift is the new length of the array. So after

    value = value.unshift(cday);
    

    the value variable now contains a number, not the array.

    value = [1, 2, 3, 4];
    value = value.unshift(10);
    console.log(value);

    Just write

    value.unshift(cday);
    

    without reassigning the variable.