Skip to content
This repository has been archived by the owner on Aug 2, 2022. It is now read-only.

Commit

Permalink
Support list 'count' function #43
Browse files Browse the repository at this point in the history
  • Loading branch information
chiquitinxx committed Mar 1, 2015
1 parent 51b9b3a commit 055efc3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
18 changes: 18 additions & 0 deletions src/main/resources/META-INF/resources/grooscript.js
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,24 @@
this.splice(0, this.length)
};

Array.prototype.count = function(value) {
var i, result = 0;
if (typeof value === "function") {
for (i = 0; i < this.length; i++) {
if (gs.bool(value(this[i]))) {
result++;
}
}
} else {
for (i = 0; i < this.length; i++) {
if (gs.equals(value, this[i])) {
result++;
}
}
}
return result;
};

/////////////////////////////////////////////////////////////////
//list - [] from groovy
/////////////////////////////////////////////////////////////////
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/META-INF/resources/grooscript.min.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class TestContributors extends Specification {
'contribution/MrHakiCategories' | _
'contribution/MrHakiTraits1' | _
'contribution/MrHakiTraits2' | _
'contribution/MrHakiCountList' | _
}

def 'test alex anderson' () {
Expand Down
15 changes: 15 additions & 0 deletions src/test/resources/contribution/MrHakiCountList.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package contribution

def list = [0, 1, 2, 1, 1, 3, 2, 0, 1]

assert 9 == list.size()
assert 2 == list.count(0)
assert 4 == list.count(1)
assert 2 == list.count(2)
assert 1 == list.count(3)

def listItems = ['Groovy', 'Grails', 'Java']
assert listItems.count { it.startsWith('G') } == 2

def numbers = [1, 2, 3, 4]
assert numbers.count { it > 2 } == 2

0 comments on commit 055efc3

Please sign in to comment.