/* * @nevware21/ts-utils * https://github.com/nevware21/ts-utils * * Copyright (c) 2022 NevWare21 Solutions LLC * Licensed under the MIT license. */ import { LENGTH, UNDEF_VALUE } from "../internal/constants"; import { createIterator, CreateIteratorContext } from "./create"; /** * Create an iterator which is backed by the provided array, unlike a normal * array iterators where the array cannot be modified function creates * a shallow copy of the array using `slice()` so that you are free to modify * the original array. * * This will still return an iterator if the provided `values` is null or * undefined which will result in no entries. * @since 0.4.2 * @group Iterator * @param values - The source array to create an iterator from * @returns A new iterator * @example * ```ts * let cnt = 0; * let values = []; * iterForOf(createArrayIterator([10, 20, 5, 15]), (value) => { * cnt++; * values.push(value); * }); * ``` */ /*#__NO_SIDE_EFFECTS__*/ export function createArrayIterator(values: T[]): Iterator { let idx = -1; let theValues = values ? values.slice() : []; let len = theValues[LENGTH]; // The ctx has its own v (so setting it doesn't call an inherited setter, eg. an Object.prototype.v accessor) let ctx: CreateIteratorContext = { v: UNDEF_VALUE, n: function () { idx++; let isDone = idx >= len; if (!isDone) { // The value is set when it is read by createIterator() ctx.v = theValues[idx]; } return isDone; } }; return createIterator(ctx); }