<?php

declare(strict_types=1);

namespace App\Modules\Shared\Domain;

final class ArrayUtils
{

    public static function generate(int $length): array
    {
        return array_fill(0, $length, null);
    }

    public static function findIndex(array $array, callable $callback): int
    {
        foreach ($array as $key => $value) {
            if ($callback($value, $key)) {
                return $key;
            }
        }
        return -1;
    }

    public static function find(array $array, callable $callback)
    {

        foreach ($array as $key => $value) {
            if ($callback($value, $key)) {
                return $value;
            }
        }
        return null;
    }

    public static function each(array &$array, callable $callback): void
    {
        foreach ($array as $key => $value) {
            $callback($value, $key);
        }
    }

    public static function flatten(array $array): array
    {
        $result = [];
        foreach ($array as $value) {
            if (is_array($value)) {
                $result = array_merge($result, $value);
            } else {
                $result[] = $value;
            }
        }
        return $result;
    }

    public static function flatmap(callable $callback, array $array): array
    {
        $result = [];
        foreach ($array as $key => $value) {
            $result = array_merge($result, $callback($value, $key));
        }
        return $result;
    }
}
