# ESI Map & Reduce

Import library ESI style

``local MR = require('esi-mapreduce')``

or import library 'function' style

``````local each = require('esi-mapreduce').each
local map = require('esi-mapreduce').map
local reduce = require('esi-mapreduce').reduce``````

## Map

The MAP() method creates a new array with the results of calling a provided function on every element in the calling array.

Parameters:

tbl

table as an Array.

predcate

function (value, index).

Returns

table

Usage:

``````local numbers = { 1, 4, 9 }
local roots = MR:MAP(numbers, function(number)
return math.sqrt(number)
end)
-- roots is { 1, 2, 3 }``````

## Reduce

The REDUCE() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Parameters:

tbl

table as an Array.

predcate

function (accumulator, value, index, tbl).

inital value Returns | any

Usage:

Calculate summary:

``````local total = MR:REDUCE({ 0, 1, 2, 3 }, function(sum, value)
return sum + value;
end, 0)
-- total is 6``````

Flatten array:

``````local flattened = MR:REDUCE({ {0, 1}, {2, 3}, {4, 5} }, function(a, b)
return MR:EACH(b, function(b_item)
table.insert(a, b_item)
end
end, {})
-- flattened { 0, 1, 2, 3, 4, 5 }``````

## Map and Reduce

Find highest number:

``````local mapped = MR:MAP({ { x = 22}, { x = 42} }, function(cur)
return cur.x
end)
local reduced = MR:REDUCE(mapped, function(max, cur)
return math.max(max, cur)
end)
-- result is 42``````

Return the number which is higher than 100:

``````local mapped = MR:MAP({ { x = 22}, { x = 42} }, function(cur)
return cur.x
end)
local reduced = MR:REDUCE(mapped, function(max, cur)
return math.max(max, cur)
end, 100)
-- no value in array was higher than 100.
-- result is 100``````

## Each

The internal iterator is also exposed.

Parameters:

tbl

table as an Array.

closure

function (value, index). if this function returns `false` the iteration will stop.

Returns

nil

Usage:

``````local reduce = require('esi-mapreduce').reduce

each(list, function(item, idx)
-- do stuff
-- Stop when item.value is zero
return item.value ~= 0
end)``````
``````local MR = require('esi-mapreduce')

MR:EACH(list, function(item)
-- do stuff
-- Stop when item.value is zero
return item.value ~= 0
end)``````