2009-04-08

polyglot: html / javascript for the win!

reminder: this article is part of a serie.

still ready for more polyglot action? then let's continue. today's language is a bit special, since it's targetting the browser. we're indeed going to craft a mix of html and javascript, the goal being that firefox renders the file as the 10 first fibonacci numbers. it's not that difficult, using the onload argument of the body tag. here's the html / javascript snippet:


<html><script language="javascript">
function foo_it () {
var i = 0
var n1 = 1
var n2 = 1
document.writeln(n1)
while (i < 9) {
n3=n1+n2
n1=n2
n2=n3
document.write("<br>",n1)
i++
}
}
</script><body onload="foo_it()"></body></html>


the nice thing is that if the html is well written, everything outside the <html> tags will be ignored. so, once again, let's put this at the end of our file. but we have a problem: we cannot have * fortran comments in the middle of our javascript code! and we cannot use the /* */ comments, since we're already inside a c comment... a first solution would be to put everything on a single line - but we can do better. since * is the multiply operator in javascript, let's create a temp variable foo that will be multiplied in place with *=. and we can then insert our code (compacted on 4 lines):


[...]
* <html><script language="javascript">function foo_it () { var foo; foo
*= 2; var i=0; var n1=1; var n2=1; document.writeln(n1); foo
*= 3; while ( i<9 ) { n3=n1+n2; n1=n2; n2=n3; document.write("<br>",n1); foo
*= 4; i++ } } </script><body onload="foo_it()"></body></html>
[...]


our tests still pass, and opening this file in firefox (after renaming it to html, in order for firefox to render it as html, not as plain text) yields the famous sequence. unfortunately, this test cannot be scripted, because of javascript...

the latest version of the program can be seen here, and now supports 9 languages. on a parallel note, is it me or are those blog entries getting smaller and smaller? :-)

anyway, that was today's entry...

No comments:

Post a Comment