Skip to content

Commit

Permalink
Merge pull request #2404 from cacaodev/CPArray-mapUsingBlock
Browse files Browse the repository at this point in the history
New: CPArray -arrayByApplyingBlock:
  • Loading branch information
cacaodev committed Jan 16, 2016
2 parents e260632 + 8c67eee commit e172217
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
19 changes: 19 additions & 0 deletions Foundation/CPArray/_CPArray.j
Expand Up @@ -880,6 +880,25 @@ Returns a hash for the object. Unlike Cocoa, the hash value does not take conten
return join.call([self _javaScriptArrayCopy], aString);
}

/*!
Returns an Array formed by applying a function to the objects in the receiver.
@param aFunction a function taking two arguments: (element, index).
@return an Array containing the transformed elements.
*/
- (CPArray)arrayByApplyingBlock:(Function/*element, index*/)aFunction
{
var result = [],
count = [self count];

for (var idx = 0; idx < count; idx++)
{
var obj = aFunction([self objectAtIndex:idx], idx);
[result addObject:obj];
}

return result;
}

// Creating a description of the array

/*!
Expand Down
14 changes: 13 additions & 1 deletion Foundation/CPArray/_CPJavaScriptArray.j
Expand Up @@ -233,6 +233,19 @@ var concat = Array.prototype.concat,
return join.call(self, aString);
}

- (CPArray)arrayByApplyingBlock:(Function/*element, index*/)aFunction
{
var result = [];

for (var idx = 0; idx < self.length; idx++)
{
var obj = aFunction(self[idx], idx);
result.push(obj);
}

return result;
}

- (void)insertObject:(id)anObject atIndex:(CPUInteger)anIndex
{
if (anIndex > self.length || anIndex < 0)
Expand Down Expand Up @@ -335,7 +348,6 @@ var concat = Array.prototype.concat,
[super addObjectsFromArray:anArray];
}


- (id)copy
{
return slice.call(self, 0);
Expand Down
17 changes: 17 additions & 0 deletions Tests/Foundation/CPArrayTest.j
Expand Up @@ -705,6 +705,23 @@
[self assert:[1, [CPNull null], "3"] equals:anArray];
}

- (void)testArrayByApplyingBlock
{
var arr = @[@"a", @"b", @"c", @"d"];

var mapped = [arr arrayByApplyingBlock:function(obj, idx)
{
return obj + "_" + idx;
}];

[self assert:[mapped count] equals:[arr count]];

[arr enumerateObjectsUsingBlock:function(obj, idx, stop)
{
[self assert:mapped[idx] equals:(obj + "_" + idx)];
}];
}

@end

@implementation AlwaysEqual : CPObject
Expand Down

0 comments on commit e172217

Please sign in to comment.