The concept of Fibonacci Sequence or Fibonacci Number is widely used in many programming books.
It could be defined via the formula:In ES5
In ES6 there is a feature so called generatorFunction which can achieve the calculation of Fibonacci Sequence in a very convenient way. But before we really enjoy the built-in language feature, let’s first see how to simulate it in ES5.
Here I use the closure in JavaScript to store the current round of calculation and return a new function for next round trigger.Suppose I would like to get a series of result and I am too lazy to call next again and again, then I write a tool function to ease my life:Then I can get 10 rounds of calculation result via a single shot:
console.log(take(10, fib(1,1)));
Result in console:
In ES6
Now we have generatorFunction which makes life pretty easier.
The complete source code:How does this native function generator work
In line 40~47 we get a function generator with ES6 grammar function *().
Within the body we declare an endless loop to calculate Fibonacci sequence.
In line 49 we call this generator via () and store its result via variable fib. Here the code in line 41~45 is never executed so far.nstead, the variable fib just holds a ITERATOR reference to function generator fib_generator.
This ITERATOR has a built-in method next supported by ES6. When this next method is called ONCE, the body in fib_generator is then executed ONCE as well.
Now let’s step into next call for the first time:Pay attention to the callstack change:Once yield is executed, the current iteration result is returned from function generator to consumer:Change the consumer code a little bit to make result returned by yield more clearly understood:Now it is clear that yield keyword returns an object with one attribute which stores current calculated result, and a boolean done flag to indicate whether the function generator has ended. In my case it is always false which makes sense since I declare a while(true) inside it.Final result:
In ABAP
In this simple report ( written by my colleague Lin Xun ), two different calculation approaches are demonstrated:Execute report you can find out that the second approach to calculate using ABAP internal table is greatly faster than the first solution.
Christian Drumm has also provided another approach in his blog Functional ABAP – Functional Programming in ABAP ?!Consumer code:Further reading
I have written a series of blogs which compare the language feature among ABAP, JavaScript and Java. You can find a list of them below:
Lazy Loading, Singleton and Bridge design pattern in JavaScript and in ABAP
Functional programming – Simulate Curry in ABAP
Functional Programming – Try Reduce in JavaScript and in ABAP
Simulate Mockito in ABAP
A simulation of Java Spring dependency injection annotation @Inject in ABAP
Singleton bypass – ABAP and Java
Weak reference in ABAP and Java