Algorithm practise in JavaScript