UNPKG

ldm-partition

Version:
36 lines 1.55 kB
"use strict"; // Based on https://en.wikipedia.org/wiki/Largest_differencing_method Object.defineProperty(exports, "__esModule", { value: true }); function partition(items, k = 2, getWeight = (x) => Number(x)) { const jobs = [...items].map((x) => [[x], ...[...Array(k - 1)].map(() => [])]); while (jobs.length > 1) { const [a, b] = select2(jobs, getWeight); const [jobA, jobB] = [jobs[a], jobs[b]]; const merged = jobA.map((l, i) => [...l, ...jobB[jobB.length - 1 - i]]); const cache = new Map(); merged.forEach((list) => cache.set(list, weigh(list, getWeight))); merged.sort((l1, l2) => { var _a, _b; return ((_a = cache.get(l2)) !== null && _a !== void 0 ? _a : 0) - ((_b = cache.get(l1)) !== null && _b !== void 0 ? _b : 0); }); jobs[a] = merged; jobs.splice(b, 1); } return jobs.length == 0 ? [...Array(k)].map(() => []) : jobs[0]; } exports.default = partition; function select2(buckets, getWeight) { const diffs = buckets.map((it) => measureDiff(it, getWeight)); const max1 = Math.max(...diffs); const a = diffs.indexOf(max1); diffs[a] = -Infinity; const max2 = Math.max(...diffs); const b = diffs.indexOf(max2); return [a, b]; } function measureDiff(bucket, getWeight) { const max = weigh(bucket[0], getWeight); const min = weigh(bucket[bucket.length - 1], getWeight); return max - min; } function weigh(list, getWeight) { return list.reduce((sum, it) => sum + getWeight(it), 0); } //# sourceMappingURL=index.js.map