Skip to content

Array support #11

@bobmulder

Description

@bobmulder

Most methods we have support types like int, float, string, and the Number instance itself.

Usecase

I do have usecases where I have an array of numbers (or any other type as seen above), which I want to sum up, or subtract. Think of an array of orderlines where you want to calculate the total from.

In this case you need to create a foreach loop like so:

$orderlines = [20, 40, 22, 45, 16];
$result = Number::create(0);

foreach ($orderslines as $orderline) {
  $result = $total->add($orderline)
}

// $result will be 143

As you see this takes four lines to calculate the total of the array.

Solution

There are multiple solutions:

Array support for common methods

For the common methods we have (like sum and subtract) we can add array support. Code would look like this:

$orderlines = [20, 40, 22, 45, 16];

$result = Number::create(0)->add($orderlines);

// $result will be 143

New method total

If we do not want to harm our existing methods (for any reason), we could introduce the total method which accepts an array, and calculates the... eh yes, total ;). That value can be used to add or subtract. Code would look like this:

$orderlines = [20, 40, 22, 45, 16];

$total = Number::total($orderlines);
$result = Number::create(0)->add($total);

// $result will be 143

One reason for this option I can think of is that we do not want our methods like sum and subtract to worry about 'complex' types like arrays. They should just do their small job.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions