Merge pull request #220 from bjorn/count_predicate

Added Sequence.count(predicate)
This commit is contained in:
Bob Nystrom
2015-03-23 07:35:17 -07:00
7 changed files with 52 additions and 2 deletions

View File

@ -16,6 +16,16 @@ class Sequence {
return result
}
count(f) {
var result = 0
for (element in this) {
if (f.call(element)) {
result = result + 1
}
}
return result
}
map(f) {
var result = new List
for (element in this) {

View File

@ -11,11 +11,11 @@ Appends `item` to the end of the list.
### **clear**()
Removes all items from the list.
Removes all elements from the list.
### **count**
The number of items in the list.
The number of elements in the list.
### **insert**(index, item)

View File

@ -34,6 +34,24 @@ Otherwise, returns `false`.
Returns whether the sequence contains any element equal to the given element.
### **count**
The number of elements in the sequence.
Unless a more efficient override is available, this will iterate over the
sequence in order to determine how many elements it contains.
### **count**(predicate)
Returns the number of elements in the sequence that pass the `predicate`.
Iterates over the sequence, passing each element to the function `predicate`
and counting the number of times the returned value evaluates to `true`.
:::dart
[1, 2, 3].count {|n| n > 2} // 1.
[1, 2, 3].count {|n| n < 4} // 3.
### **join**(sep)
Returns a string representation of the list. The string representations of the

View File

@ -62,6 +62,16 @@ static const char* libSource =
" return result\n"
" }\n"
"\n"
" count(f) {\n"
" var result = 0\n"
" for (element in this) {\n"
" if (f.call(element)) {\n"
" result = result + 1\n"
" }\n"
" }\n"
" return result\n"
" }\n"
"\n"
" map(f) {\n"
" var result = new List\n"
" for (element in this) {\n"

View File

@ -0,0 +1,6 @@
var a = [1, 2, 3]
IO.print(a.count {|x| x > 3 }) // expect: 0
IO.print(a.count {|x| x > 1 }) // expect: 2
IO.print([].count {|x| true }) // expect: 0

View File

@ -0,0 +1,3 @@
var a = [1, 2, 3]
IO.print(a.count {|x| "truthy" }) // expect: 3

View File

@ -0,0 +1,3 @@
var a = [1, 2, 3]
a.count("string") // expect runtime error: String does not implement 'call(_)'.