Scroll back to the top

JavaScript Test Tasks

[ javascript ]

I passed the simple coding test during registration on the web site few days ago. There are 3 tasks:

1. Sort the numbers by frequency and leave original order for equal frequency numbers

I implemented modified bubble-sort for both the sorting and the saving original order

const input = '1 1 3 5 8 8 4 8 9';

var output = countSort(input);
console.log(output);

function countSort(s) {
  const a = s.split(' ').map(ch => +ch);
  const counters = {};
  a.forEach(x => {
    if (!counters[x])
      counters[x] = 1;
    else
      counters[x] += 1;
  });

  let process = true;
  while (process) {
    process = false;
    for (let i = 0, n = a.length; i < n - 1; i++)
      if (counters[a[i]] < counters[a[i+1]]) {
        const c = a[i];
        a[i] = a[i+1];
        a[i+1] = c;
        process = true;
      }
  }
  return a.join(' ');
}

2. Perfect numbers

6, 28, 496, …

for (let i = 0; i < 500; i++) {
  if (isPerfect(i))
    console.log(i);
}

function isPerfect(n) {
  if (n < 6)
    return false;
  let s = 0;
  for (let i = 1, count = n / 2; i <= count; i++) {
    if (n % i === 0)
      s += i;
  }
  return s === n;
}

3. String rank

I’m afraid there is be some more elegant pure regex solution. But I’ve done dummy straightforward solution.

console.log(stringRank('onion')); // on - 2
console.log(stringRank('codenrock')); // 0
console.log(stringRank('undergrounder')); // under - 5

function stringRank(s) {
  const a = s.toLowerCase().split('');
  if (a.length <= 1)
    return 0;
  let result = 0;
  for (let i = 1, n = a.length; i < n; i++) {
    let j;
    for (j = 0; j < i; j++)
      if (a[j] !== a[n-i+j])
        break;
    if (j === i)
      result = i;
  }
  return result;
}

Happy coding!