function weighted_samples({ vec, weight_id = null, n }) {
let total_weight = 0;
let to_sample = [];
vec.forEach((d, i) => {
const w = weight_id ? d[weight_id] : 1;
if (w > 0) {
total_weight += w;
to_sample.push({ w, i });
}
});
const sampled = [];
for (let k = 0; k < n; k++) {
const end_weight = Math.random() * total_weight;
let cumulative_weight = 0;
for (let j = 0; j < to_sample.length; j++) {
const { w, i } = to_sample[j];
cumulative_weight += w;
if (cumulative_weight >= end_weight) {
total_weight -= w;
sampled.push(to_sample.splice(j, 1)[0]);
break;
}
if (total_weight === 0 || to_sample.length === 0) break;
}
}
return sampled.map(d => vec[d.i]);
}