/**
 * D3 Array Polyfill - Lightweight array utility functions.
 *
 * This is a drop-in replacement for d3-array, implementing only the methods
 * used in the Vega chart rendering system: min, max, extent, and map.
 *
 * @see VD-5022 - [Zero Dependencies] remove d3 dependency
 */
/**
 * Returns the minimum value in the array.
 * Mimics d3.min().
 *
 * @template T
 * @param {T[]} array - Array of values.
 * @param {Function} [accessor] - Optional accessor function.
 * @returns {number | undefined} The minimum value, or undefined for empty arrays.
 */
export function min(array, accessor) {
  let result;
  for (let i = 0; i < array.length; i++) {
    const value = accessor ? accessor(array[i], i) : Number(array[i]);
    if (value != null && !Number.isNaN(value)) {
      if (result === undefined || value < result) {
        result = value;
      }
    }
  }
  return result;
}
/**
 * Returns the maximum value in the array.
 * Mimics d3.max().
 *
 * @template T
 * @param {T[]} array - Array of values.
 * @param {Function} [accessor] - Optional accessor function.
 * @returns {number | undefined} The maximum value, or undefined for empty arrays.
 */
export function max(array, accessor) {
  let result;
  for (let i = 0; i < array.length; i++) {
    const value = accessor ? accessor(array[i], i) : Number(array[i]);
    if (value != null && !Number.isNaN(value)) {
      if (result === undefined || value > result) {
        result = value;
      }
    }
  }
  return result;
}
/**
 * Returns the [min, max] of the array.
 * Mimics d3.extent().
 *
 * @template T
 * @param {T[]} array - Array of values.
 * @returns {[T, T] | [undefined, undefined]} Tuple of [min, max], or [undefined, undefined] for empty arrays.
 */
export function extent(array) {
  let minVal;
  let maxVal;
  for (const value of array) {
    if (value != null && value >= value) {
      if (minVal === undefined || value < minVal) {
        minVal = value;
      }
      if (maxVal === undefined || value > maxVal) {
        maxVal = value;
      }
    }
  }
  if (minVal === undefined || maxVal === undefined) {
    return [undefined, undefined];
  }
  return [minVal, maxVal];
}
/**
 * Maps each element of the array through a transform function.
 * Mimics d3.map() (the array mapping function from d3-array, not the Map collection).
 *
 * @template T
 * @template U
 * @param {T[]} array - Input array.
 * @param {Function} mapper - Transform function called with (element, index).
 * @returns {U[]} New array of transformed values.
 */
export function map(array, mapper) {
  return array.map(mapper);
}
