skip to Main Content

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?

2

Answers


  1. 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}));
    Login or Signup to reply.
  2. You can achieve something similar by passing in an object

    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({arr: [0,4,9,2], k: 2}))
    

    The difference is that you don’t have positional arguments anymore, you need to specify the key of each value (in this case arr: [0, 4, 9, 2])

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search