Issam E. Maghni | f796a09 | 2022-10-09 20:25:26 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Affero General Public License as |
| 6 | * published by the Free Software Foundation; either version 3 of the |
| 7 | * License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Affero General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Affero General Public |
| 15 | * License along with this program. If not, see |
| 16 | * <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | import { createRequire } from 'node:module'; |
| 19 | |
| 20 | export function* itRange(lo: number, hi: number) { |
| 21 | for (let i = lo; i < hi; ++i) { |
| 22 | yield i; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | export function* itMap<T, U>(it: Iterable<T>, cb: (value: T, index: number) => U) { |
| 27 | let i = 0; |
| 28 | for (const item of it) { |
| 29 | yield cb(item, i++); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | export function* itFilter<T>(it: Iterable<T>, cb: (value: T, index: number) => boolean) { |
| 34 | let i = 0; |
| 35 | for (const item of it) { |
| 36 | if (cb(item, i++)) { |
| 37 | yield item; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | export const itToArr = <T>(it: Iterable<T>) => Array.from(it); |
| 43 | |
| 44 | export const itToMap = <T, U>(it: Iterable<[T, U]>) => { |
| 45 | const m = new Map<T, U>(); |
| 46 | for (const [k, v] of it) { |
| 47 | m.set(k, v); |
| 48 | } |
| 49 | return m; |
| 50 | }; |
| 51 | |
| 52 | export const require = createRequire(import.meta.url); |