|
| 1 | +/* |
| 2 | + * @nevware21/ts-utils |
| 3 | + * https://github.com/nevware21/ts-utils |
| 4 | + * |
| 5 | + * Copyright (c) 2026 NevWare21 Solutions LLC |
| 6 | + * Licensed under the MIT license. |
| 7 | + */ |
| 8 | + |
| 9 | +import { ArrProto } from "../internal/constants"; |
| 10 | +import { _throwIfNullOrUndefined } from "../internal/throwIf"; |
| 11 | +import { _unwrapFunctionWithPoly } from "../internal/unwrapFunction"; |
| 12 | +import { createIterableIterator } from "../iterator/create"; |
| 13 | +import { mathToInt } from "../math/to_int"; |
| 14 | + |
| 15 | +/** |
| 16 | + * Returns an iterator over all numeric keys from `0` to `length - 1`. |
| 17 | + * |
| 18 | + * This uses `Array.prototype.keys()` when available and falls back to {@link polyArrKeys}. |
| 19 | + * Unlike {@link arrIndexKeys}, this always iterates all index positions, including holes. |
| 20 | + * @since 0.14.0 |
| 21 | + * @function |
| 22 | + * @group Array |
| 23 | + * @group ArrayLike |
| 24 | + * @group Iterator |
| 25 | + * @param value - The array-like value to get key iterator for. |
| 26 | + * @returns An iterable iterator of numeric index keys. |
| 27 | + * @example |
| 28 | + * ```ts |
| 29 | + * arrFrom(arrKeys(["a", "b", "c"])); |
| 30 | + * // [0, 1, 2] |
| 31 | + * |
| 32 | + * const sparse: any[] = []; |
| 33 | + * sparse[2] = "c"; |
| 34 | + * arrFrom(arrKeys(sparse)); |
| 35 | + * // [0, 1, 2] |
| 36 | + * ``` |
| 37 | + */ |
| 38 | +export const arrKeys: <T = any>(value: ArrayLike<T>) => IterableIterator<number> = (/*#__PURE__*/_unwrapFunctionWithPoly("keys", ArrProto as any, polyArrKeys) as any); |
| 39 | + |
| 40 | +/** |
| 41 | + * Polyfill implementation of `Array.prototype.keys()` for array-like values. |
| 42 | + * @since 0.14.0 |
| 43 | + * @group Array |
| 44 | + * @group ArrayLike |
| 45 | + * @group Iterator |
| 46 | + * @group Polyfill |
| 47 | + * @param value - The array-like value to get key iterator for. |
| 48 | + * @returns An iterable iterator of numeric index keys. |
| 49 | + * @example |
| 50 | + * ```ts |
| 51 | + * arrFrom(polyArrKeys(["a", "b", "c"])); |
| 52 | + * // [0, 1, 2] |
| 53 | + * |
| 54 | + * arrFrom(polyArrKeys({ length: 3, 0: "a", 2: "c" })); |
| 55 | + * // [0, 1, 2] |
| 56 | + * ``` |
| 57 | + */ |
| 58 | +/*#__NO_SIDE_EFFECTS__*/ |
| 59 | +export function polyArrKeys<T = any>(value: ArrayLike<T>): IterableIterator<number> { |
| 60 | + _throwIfNullOrUndefined(value); |
| 61 | + |
| 62 | + let idx = -1; |
| 63 | + let len = mathToInt(value.length); |
| 64 | + if (len < 0) { |
| 65 | + len = 0; |
| 66 | + } |
| 67 | + |
| 68 | + return createIterableIterator<number>({ |
| 69 | + n: function() { |
| 70 | + idx++; |
| 71 | + let isDone = idx >= len; |
| 72 | + if (!isDone) { |
| 73 | + this.v = idx; |
| 74 | + } |
| 75 | + |
| 76 | + return isDone; |
| 77 | + } |
| 78 | + }); |
| 79 | +} |
0 commit comments