JavaScript Algorithm