Search code examples
javascriptparameters

Python-like function parameters in JavaScript


I'm trying to emulate the functionality of random.choices in the Python standard library, in JavaScript. I tried this code:

function choices(arr, weights = null, k = 1) {
    let out = [];
    if (weights != null) {
        // implemented later
    } else if (k == 1) {
        return arr[Math.floor(Math.random() * arr.length)]
    } else {
        for (let i = 0; i < k; i++) {
            out.push(arr[Math.floor(Math.random() * arr.length)])
        }
        return out;
    }
}

console.log(choices([0,4,9,2], k = 2)

I want the k = 2 part to pass a keyword parameter, like how they work in Python.

But k just shows up as any:

VSCode hovering over the k parameter, saying any.

How can I get the desired effect?


Solution

  • In JavaScript there is a somewhat related feature, but you have to define the parameter list differently. Think of it as explicitly defining the kwargs dict (in Python terminology). Also the caller must pass an object (dict) to match it. You can make that single parameter optional by assigning a default for it (as a whole):

    function choices(arr, {weights=null, k=1}={}) {
        let out = [];
        if (weights != null) {
            // implemented later
        } else if (k == 1) {
            return arr[Math.floor(Math.random() * arr.length)]
        } else {
            for (let i = 0; i < k; i++) {
                out.push(arr[Math.floor(Math.random() * arr.length)])
            }
            return out;
        }
    }
    
    console.log(choices([0,4,9,2], {k: 2}));