Changed the python algorithm to javascript (I use the latter elsewhere, no reason to keep a duplicate)