For some reason solidity doesn't allow to push values into memory array

> Member "push" is not available in bytes32[] memory outside of
> storage.

Here is sample contract code:

    pragma solidity ^0.4.21;
    
    contract Foo {
        function getRange(uint n) public pure returns(uint[]) {
            uint[] memory result;
            for (uint i = 0; i < n; i++)
                if (someCondition(i))
                   result.push(i);
            return result;
        }
    }

I could allocate maximum possible array of size `n` and then shrink it, but it may hurt performance (`n` could be in order of magnitude of `100000` while final length of result is `0..100`). For example, `someCondition` could be `isPrime`. In this case we have large N (which makes impossible to preallocate an array) and small list of resulting prime numbers.

How could it be done?


  [1]: https://github.com/ethereum/dapp-bin/blob/master/library/stringUtils.sol