Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What could this line of Javascript code possibly do?

Tags:

javascript

I just stumbled upon a line of code in a project I'm currently working in. I feel I'm decent at Javascript but to be honest, I have no clue as of what the following line of code actually does:

var date = new (Function.prototype.bind.apply(Date, [null,].concat(buildDateParams(spec, base))));

Can someone of you Javascript gurus possibly shed some light on this?

buildDateParams seems to build an array of values. For completeness' sake, here's the function:

function buildDateParams(spec, base) {
    if (!spec.match(specRegExp)) {
        throw new Error('Invalid spec string');
    }
    var specParts = spec.toLowerCase().split(':');
    let params = [];
    for (let fieldIndex in fields) {
        let field = fields[fieldIndex];
        let specPart = (fieldIndex < specParts.length)
            ? specParts[fieldIndex]
            : '0';
        if (!specPart.length) {
            specPart = 'b';
        }
        let param = 0;
        if (specPart.substr(0, 1) === 'b') {
            param = base[field.getter]();
            specPart = specPart.substr(1);
        }
        if (specPart.length) {
            param += parseInt(specPart);
        }
        params.push(param);
    }
    return params;
}
like image 330
connexo Avatar asked May 10 '17 13:05

connexo


1 Answers

It's sort-of a complicated version of

Date.bind(null, buildDateParams(spec, base));

except one that works; the idea is that it wants to bind the Date constructor to a set of parameters that are generated by that buildDateParams() function.

With the ES2015 spread syntax, it'd work to write

Date.bind(null, ... buildDateParams(spec, base));

It's just creating a function that returns a Date instance according to some pre-arranged parameters.

Also, because of that stray comma in the [null,] array initializer, it might have issues in IE (though a modern IE with .bind() might not interpret that array as having two elements).

like image 195
Pointy Avatar answered Oct 28 '22 05:10

Pointy