ported solution to javascript