mirror of
https://github.com/wren-lang/wren.git
synced 2026-01-11 22:28:45 +01:00
Merge pull request #220 from bjorn/count_predicate
Added Sequence.count(predicate)
This commit is contained in:
@ -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) {
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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"
|
||||
|
||||
6
test/core/list/count_predicate.wren
Normal file
6
test/core/list/count_predicate.wren
Normal 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
|
||||
@ -0,0 +1,3 @@
|
||||
var a = [1, 2, 3]
|
||||
|
||||
IO.print(a.count {|x| "truthy" }) // expect: 3
|
||||
3
test/core/list/count_predicate_non_function_arg.wren
Normal file
3
test/core/list/count_predicate_non_function_arg.wren
Normal file
@ -0,0 +1,3 @@
|
||||
var a = [1, 2, 3]
|
||||
|
||||
a.count("string") // expect runtime error: String does not implement 'call(_)'.
|
||||
Reference in New Issue
Block a user