Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading