JS algorithm