|
| 1 | +// Import {Empty} from '../../3-tree/index.js'; |
| 2 | + |
| 3 | +import {Empty} from '../../3-tree/implementations/0-Empty.js'; |
| 4 | +import { |
| 5 | + THRESHOLD as MEDIUM_THRESHOLD, |
| 6 | + _from_medium_list, |
| 7 | + _from_largest_medium_list, |
| 8 | +} from './_from_medium_list.js'; |
| 9 | + |
| 10 | +function increment(trees, tree) { |
| 11 | + // eslint-disable-next-line no-bitwise,unicorn/prefer-math-trunc |
| 12 | + const n = trees.length | 0; |
| 13 | + // eslint-disable-next-line no-bitwise,unicorn/prefer-math-trunc |
| 14 | + for (let i = 0; i !== n; i = (i + 1) | 0) { |
| 15 | + if (trees[i] === null) { |
| 16 | + trees[i] = tree; |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + tree = trees[i].concat(tree); |
| 21 | + trees[i] = null; |
| 22 | + } |
| 23 | + |
| 24 | + trees.push(tree); |
| 25 | +} |
| 26 | + |
| 27 | +function sum(M, trees) { |
| 28 | + let result = new Empty(M); |
| 29 | + for (const tree of trees) { |
| 30 | + if (tree !== null) { |
| 31 | + result = tree.concat(result); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + return result; |
| 36 | +} |
| 37 | + |
| 38 | +export function _from_iterable(M, iterable) { |
| 39 | + // Return new Empty(M).append(iterable); |
| 40 | + const it = iterable[Symbol.iterator](); |
| 41 | + const trees = []; |
| 42 | + for (;;) { |
| 43 | + const list = []; |
| 44 | + // eslint-disable-next-line no-bitwise,unicorn/prefer-math-trunc |
| 45 | + for (let i = MEDIUM_THRESHOLD; i !== 0; i = (i - 1) | 0) { |
| 46 | + const event = it.next(); |
| 47 | + if (event.done) { |
| 48 | + increment(trees, _from_medium_list(M, list)); |
| 49 | + return sum(M, trees); |
| 50 | + } |
| 51 | + |
| 52 | + list.push(event.value); |
| 53 | + } |
| 54 | + |
| 55 | + increment(trees, _from_largest_medium_list(M, list)); |
| 56 | + } |
| 57 | +} |
0 commit comments