Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wren/core: Add Sequence::find. #898

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/site/modules/core/sequence.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ Iterates over the sequence, passing each element to the given `function`.
["one", "two", "three"].each {|word| System.print(word) }
</pre>

### **find**(predicate), **find**(it, predicate)

Returns an iterator on the sequence that pass the function `predicate`,
starting from the begining of the sequence or `it` if provided.

It is a runtime error if `it` is not a valid iterator value on the sequence.

### **isEmpty**

Returns whether the sequence contains any elements.
Expand Down
10 changes: 10 additions & 0 deletions src/vm/wren_core.wren
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ class Sequence {
}
}

find(predicate) { find(iterate(null), predicate) }

find(it, predicate) {
while(it) {
if (predicate.call(iteratorValue(it))) break
it = iterate(it)
}
return it
}

isEmpty { iterate(null) ? false : true }

map(transformation) { MapSequence.new(this, transformation) }
Expand Down
10 changes: 10 additions & 0 deletions src/vm/wren_core.wren.inc
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ static const char* coreModuleSource =
" }\n"
" }\n"
"\n"
" find(predicate) { find(iterate(null), predicate) }\n"
"\n"
" find(it, predicate) {\n"
" while(it) {\n"
" if (predicate.call(iteratorValue(it))) break\n"
" it = iterate(it)\n"
" }\n"
" return it\n"
" }\n"
"\n"
" isEmpty { iterate(null) ? false : true }\n"
"\n"
" map(transformation) { MapSequence.new(this, transformation) }\n"
Expand Down
8 changes: 8 additions & 0 deletions test/core/sequence/find.wren
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

var data = 0...100

System.print(data.find {|value| value == -1 }) // expect: false
System.print(data.iteratorValue(data.find {|value| value == 42 })) // expect: 42
System.print(data.find {|value| value == 100 }) // expect: false

System.print(data.iteratorValue(data.find(data.find {|value| value == 42 }) {|value| value %15 == 0})) // expect: 45