Day 14 of 21 Days of Javascript

I'm on a chunky chapter where I need to read all the code of a simple robot program and fully understand it before attempting the related exercises. This means this chapter will be a slow one. I've read it once already, but will re-read it again tomorrow before attempting the exercises.

Meanwhile, here's a brief log on today's learning.

No Knowledge, No Wisdom.

You need a bank of knowledge to have good judgement and wisdom to do things well. This applies to any skill, as I was reminded today.

To warm up for my Javascript work, I completed a short online test. The task is to take a list of numbers and sort them from small to large. For example an input of [112, 3, 5, -76] should return [-76, 3, 5, 112] .

Someone with good knowledge of Javascript and judgement (aka 'wisdom'), would solve this task with one line of code:

function sortNums(nums) {
  return nums.sort((a, b) => a - b);
}

But I'm new to Javascript and have little knowledge of the language and its syntax. This means my solutions are almost always naive. Here's how I solved this exercise:

function findMin(nums) {
    return nums.reduce((acc, currVal) => currVal < acc ? currVal : acc, nums[0]);
}

function solution(nums){
    if (!nums || nums.length === 0) {
        return [];
    }
    let newNums = [];
    while (nums.length != 0) {
        //console.log(`Current input list is ${nums}.`)
        let currMin = findMin(nums); // find min in list
        nums.splice(nums.indexOf(currMin),1); // remove min num
        newNums.push(currMin);
    }
    return newNums;
}

console.log(solution([112,3,5,-76])); // should return [-76, 3, 5, 112]

My solution is almost 10x longer and computationally slow. Had I known that Javascript has a built-in sort method for arrays (numbers.sort((a, b) => a - b);) I would have used that knowledge for a smarter solution.

This is how learning works though. You start off naive, bumbling your way to solutions that sort of work and fail before you can benefit from experience and knowledge to do things better.