Skip to content

Commit

Permalink
reduce
Browse files Browse the repository at this point in the history
  • Loading branch information
kemsky committed Oct 14, 2015
1 parent f3662f8 commit 318243e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/com/kemsky/Stream.as
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ package com.kemsky
this.source = source == null ? [] : source;
}

// todo
// public function remove(index:int, count:uint = 1):Stream
// {
// source.splice.apply(null, [index, count].concat());
// return this;
// }
//
// public function insert(index:int, item:*, ...rest):Stream
// {
// source.splice.apply(null, [index, 0, item].concat());
// return this;
// }

/**
* Creates a new stream for all items that are not strictly equal to undefined (item !== <i>undefined</i>).
* @return A new stream that contains all items from the original stream that are not equal to <i>undefined</i>.
Expand Down Expand Up @@ -480,12 +493,13 @@ package com.kemsky
* @param initial The initial value for the accumulator.
* @return The value of accumulator.
*/
public function foldLeft(callback:Function, initial:*):*
public function foldLeft(callback:Function, initial:* = undefined):*
{
var context:* = initial;
for each (var item:* in source)
var context:* = initial === undefined ? first : initial;
var start:int = initial === undefined ? 0 : 1;
for (var i:int = start; i < source.length; i++)
{
context = callback(item, context);
context = callback(source[i], context);
}
return context;
}
Expand All @@ -496,12 +510,13 @@ package com.kemsky
* @param initial The initial value for the accumulator.
* @return The value of accumulator.
*/
public function foldRight(callback:Function, initial:*):*
public function foldRight(callback:Function, initial:* = undefined):*
{
var context:* = initial;
for each (var item:* in source.reverse())
var context:* = initial === undefined ? last : initial;
var start:int = initial === undefined ? source.length - 2 : source.length - 1;
for (var i:int = start; i > 0; i--)
{
context = callback(item, context);
context = callback(source[i], context);
}
return context;
}
Expand Down
14 changes: 14 additions & 0 deletions testSrc/com/kemsky/TestStream.as
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,13 @@ package com.kemsky
}, 10);

assertEquals(sum2, 20);

var sum3:Number = $(0, 1, 2, 3, 4).foldLeft(function (prev:Number, current:Number):Number
{
return prev + current;
});

assertEquals(sum3, 10);
}

[Test]
Expand All @@ -745,6 +752,13 @@ package com.kemsky
}, 10);

assertEquals(sum2, 20);

var sum3:Number = $(0, 1, 2, 3, 4).foldRight(function (prev:Number, current:Number):Number
{
return prev + current;
});

assertEquals(sum3, 10);
}

[Test]
Expand Down

0 comments on commit 318243e

Please sign in to comment.