import { nativePush } from "../basic/_global";
import isFlattenable from "./_isFlattenable";

/**
 * The base implementation of `flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten<T>(array: NestedArray<T>, depth: number, predicate?: (value: NestedArray<T> | T) => boolean, isStrict?: boolean, result?: Array<FlatArray<T>>): Array<FlatArray<T>> {
    predicate || (predicate = isFlattenable);
    result || (result = []);

    if (array == null) {
        return result;
    }

    let index = -1,
        length = array.length;

    while (++index < length) {
        const value = array[index];
        if (depth > 0 && predicate(value)) {
            if (depth > 1) {
                // Recursively flatten arrays (susceptible to call stack limits).
                baseFlatten(value as NestedArray<T> | Array<T>, depth - 1, predicate, isStrict, result);
            } else {
                nativePush.apply(result, value);
            }
        } else if (!isStrict) {
            result[result.length] = value as FlatArray<T>;
        }
    }
    return result;
}

export default baseFlatten;
// import isFlattenable from "./isFlattenable.js";

// /**
//  * The base implementation of `flatten` with support for restricting flattening.
//  *
//  * @private
//  * @param {Array} array The array to flatten.
//  * @param {number} depth The maximum recursion depth.
//  * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
//  * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
//  * @param {Array} [result=[]] The initial result value.
//  * @returns {Array} Returns the new flattened array.
//  */
// function baseFlatten(array, depth, predicate, isStrict, result) {
//     predicate || (predicate = isFlattenable);
//     result || (result = []);

//     if (array == null) {
//         return result;
//     }

//     for (const value of array) {
//         if (depth > 0 && predicate(value)) {
//             if (depth > 1) {
//                 // Recursively flatten arrays (susceptible to call stack limits).
//                 baseFlatten(value, depth - 1, predicate, isStrict, result);
//             } else {
//                 result.push(...value);
//             }
//         } else if (!isStrict) {
//             result[result.length] = value;
//         }
//     }
//     return result;
// }

// export default baseFlatten;
