My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Tuesday, November 07, 2006

not yield and the shortest Fibonacci function

I was joking with new JS 1.7 features, well documented in this page, when I've thought about yield keyword.

It's a strange keyword because isn't usable as the rest of JS code.

For example, alert(yield variable) generates an error but alert((yield variable)) shows an undefined value.
(I know, it is quite idiot to think that it should have some value ...)

Then I've done some test:

function fakeGenerator(){
var i = 0;
// alert(yield i++); // error
// alert((yield i++)); // undefined
yield i++; // ok

As you can see, (yield something) returns an undefined value and then this is a true expression.

!(yield variable) === true

Now You can think that a while loop should use this condiction instead of while(true) {yield variables;} ... for example:

function fakeGenerator(i){
while(!(yield i++)){}

works perfectly then maybe I could use this information to write something like this ?

function fakeGenerator(i){
while(!(yield i++));

Sure, and it works perfectly again !!!
!undefined is true and semi colon stops while loop then with an "OR" or an "AND" and a true value as condiction I could create a lot of dirty generators ... why not Fibonacci too ?

function fib(){
while((yield i)||([i,j]=[j,i+j]));

so c'mon brother, you can do it better!, said my dog ... and He was right, I can remove even OR, parentheses and why not, the last semi colon too (thanks to let block).

function fib(){let(i=0,j=1){while(!(yield i))[i,j]=[j,i+j]}};

That's what I meant for the shortest Fibonacci function, isn't that ?!?

Then ... What's up ?
I wrote this stupid post just to tell You that sometimes You don't need the "while(true)" condition, just switch true the "undefined yield" :)


Andrea Giammarchi said...

I just come back and anyone viewed the title error ?

It was wrong, it was the shortest Fibonacci generator ... and sorry :D

nicerobot said...


function fib(){for(let i=0,j=1;;[i,j]=[j,i+j])yield i};