js rewrite (now functional)