diff --git a/builtin/core.wren b/builtin/core.wren index 3867bda9..52ae9ac3 100644 --- a/builtin/core.wren +++ b/builtin/core.wren @@ -52,6 +52,8 @@ class Sequence { } } + isEmpty { iterate(null) ? false : true } + map(transformation) { new MapSequence(this, transformation) } where(predicate) { new WhereSequence(this, predicate) } diff --git a/doc/site/core/sequence.markdown b/doc/site/core/sequence.markdown index 01500740..4a12df95 100644 --- a/doc/site/core/sequence.markdown +++ b/doc/site/core/sequence.markdown @@ -61,6 +61,13 @@ Iterates over the sequence, passing each element to the given `function`. :::dart ["one", "two", "three"].each {|word| IO.print(word) } +### **isEmpty** + +Returns whether the sequence contains any elements. + +This can be more efficient that `count == 0` because this does not iterate over +the entire sequence. + ### **join**(sep) Returns a string representation of the sequence. The string representations of diff --git a/src/vm/wren_core.c b/src/vm/wren_core.c index ea73909e..c382e3a9 100644 --- a/src/vm/wren_core.c +++ b/src/vm/wren_core.c @@ -66,6 +66,8 @@ static const char* coreLibSource = " }\n" " }\n" "\n" +" isEmpty { iterate(null) ? false : true }\n" +"\n" " map(transformation) { new MapSequence(this, transformation) }\n" "\n" " where(predicate) { new WhereSequence(this, predicate) }\n" diff --git a/test/core/sequence/is_empty.wren b/test/core/sequence/is_empty.wren new file mode 100644 index 00000000..30d2492d --- /dev/null +++ b/test/core/sequence/is_empty.wren @@ -0,0 +1,10 @@ +IO.print([].isEmpty) // expect: true +IO.print([1].isEmpty) // expect: false + +class InfiniteSequence is Sequence { + iterate(iterator) { true } + iteratorValue(iterator) { iterator } +} + +// Should not try to iterate the whole sequence. +IO.print((new InfiniteSequence).isEmpty) // expect: false