algorithm in javascript