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

Feature: iter\empty or add limit to iter\count #46

Closed
SamMousa opened this issue Aug 2, 2017 · 2 comments
Closed

Feature: iter\empty or add limit to iter\count #46

SamMousa opened this issue Aug 2, 2017 · 2 comments

Comments

@SamMousa
Copy link
Contributor

SamMousa commented Aug 2, 2017

Currently we have count() to count the number of elements in an iterator.

I'd love a function empty() that tells me wether an iterable is empty or not.
This could be done separately, alternatively it might be more flexible to add a limit to count:

Many uses for count compare it with some number anyway, no sense wasting time counting beyond it.

function inf() { 
    $i = 0;
    while(true) {
        yield $i++;
    }
}

function thousand() { 
    $i = 0;
    while($i < 1000) {
        yield $i++;
    }
}

// Check if empty. [infinite loop]
if (count(inf()) > 0) {

}

// Check if contains at least 50 elements. [infinite loop]
if (count(inf()) > 50) {

}

// Check if contains at least 50 elements. [1000 iterations, 950 useless]
if (count(thousand()) > 50) {

}

// Check if empty. [1000 iterations, 999 useless]
if (count(empty()) > 0) {

}

Adding a limit to count would resolve these issues:

function inf() { 
    $i = 0;
    while(true) {
        yield $i++;
    }
}

function thousand() { 
    $i = 0;
    while($i < 1000) {
        yield $i++;
    }
}


// Check if empty. [1 iterations]
if (count(inf(), 1) > 0) {

}

// Check if contains at least 50 elements. [50 iterations]
if (count(inf(), 51) > 50) {

}

// Check if contains at least 50 elements. [1000 iterations]
if (count(thousand(), 51) > 50) {

}

// Check if empty. [1 iteration]
if (count(thousand(), 1) > 0) {

}
@nikic
Copy link
Owner

nikic commented Aug 2, 2017

The parameter on count() seems rather confusing to me -- I wouldn't be able to guess what this does just by looking at the code. It's possible to obtain the same result using a combination of count and take though: if (count(take($it, 51)) > 50), which I think it clearer than the extra parameter on count().

Agree on the empty though, that looks useful. As empty is a reserved keyword, it would have to be something like isEmpty() though.

@nikic
Copy link
Owner

nikic commented Nov 10, 2017

isEmpty() function added in fed36b4 and released as part of v1.6.0.

@nikic nikic closed this as completed Nov 10, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants