@charset "UTF-8";

// @description
// * sum function.
// * Calculates the sum of numeric values in a list, including nested lists.

// @access public

// @version 1.4.0

// @author Khaled Mohamed

// @license MIT

// @repository: https://github.com/Black-Axis/sass-pire

// @namespace global

// @module global/sum

// @dependencies:
// * - meta.type-of (SASS function).
// * - list.nth (SASS function).
// * - list.length (SASS function).
// * - LibFunc.flatten-list (function).
// * - Error.throw (function).

// @param {...Number or List} $args
// * Variable number of arguments, either numbers or lists of numbers.

// @throws {Error}
// * If an argument is not a number or a list of numbers.

// @example 1
// * .example {
// *   content: sum((1px, 2px, 3px));
// * }

// @output 1
// * .example {
// *   content: 6px;
// * }

// @example 2
// * .example {
// *   content: sum((1, 2, 3, (2, 2)));
// * }

// @output 2
// * .example {
// *   content: 10;
// * }

// @example 3
// * .example {
// *   content: sum((1px, (2rem, 3rem), 4rem));
// * }

// @output 3
// * .example {
// *   content: "ERROR: Values of the list must has one unit only.";
// * }

// @example 4
// * .example {
// *   content: sum(((())));
// * }

// @output 4
// * .example {
// *   content: 0;
// * }

// @return {Number} The sum of the numeric values in the arguments.

@use "sass:meta";
@use "sass:math";
@use "sass:list";
@use "../../functions/list/flatten-list" as LibFunc;
@use "../../development-utils/toggle-error-message" as Error;

@function sum($args: ()) {
    @if meta.type-of($args) != list {
        @return Error.throw("The parameter of sum function must be in a list type.");
    } @else {
        $sum: 0;
        $flatten-list: LibFunc.flatten($args);
        $length-of-list: list.length($flatten-list);

        @if $length-of-list == 0 {
            @return 0;
        }

        $first-number-unit: math.unit(list.nth($flatten-list, 1));
        $flag: true;

        @each $item in $flatten-list {
            @if math.unit($item) != $first-number-unit {
                $flag: false;

                @return Error.throw("Values of the list must has one unit only.");
            }
        }

        @for $item from 1 through $length-of-list {
            @if meta.type-of(list.nth($flatten-list, $item)) != number {
                @return Error.throw("Values of the list must be in a number type only.");
            }

            $sum: $sum + list.nth($flatten-list, $item);
        }

        @return $sum;
    }
}
