The linear partition algorithm in pure javascript