We call this type of optimisation "stream fusion".
In an ideal world, the compiler would always know to do this for us. In practice, it's very difficult (in most languages) to determine whether this optimisation is correct.
In the README example's case, the optimisation happens to be correct because both mapping functions are pure. If they had side effects, then stream fusion might create different results than the original code. Let's make this concrete with an example.
Say our array is `[1, 2]` and our functions are `function A(n) { print("A: "+n) }` and `function B(n) { print("B: "+n) }`. Then _without_ stream fusion, we would see the following output:
```
A: 1
A: 2
B: 1
B: 2
```
_With_ stream fusion, we would see different output:
```
A: 1
B: 1
A: 2
B: 2
```
Since the mapping functions have side effects, stream fusion is not valid here.
Some languages can do automatic implicit stream fusion. Haskell is a great example of this: it's able to determine when stream fusion is correct because the language has an _effect tracking system_ where functions with side effects are distinct from functions without side effects.