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:
How can I get the desired effect?
2
Answers
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):
You can achieve something similar by passing in an object
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]
)