Home > OS >  Finding minimum number without using Math.Min() function
Finding minimum number without using Math.Min() function

Time:12-14

I am facing problem with my question below which restricted us to use Math.Min() function to obtain answer. I tried multiple ways but never seems to get the answer right.

Minimum of two numbers Let's pretend the JavaScript Math.min() function doesn't exist. Complete the following program so that the min() function returns the minimum of its two received numbers.

// TODO: write the min() function

console.log(min(4.5, 5)); // Must show 4.5

console.log(min(19, 9)); // Must show 9

console.log(min(1, 1)); // Must show 1

CodePudding user response:

One-liner using .reduce():

const min = (...args) => args.reduce((min, num) => num < min ? num : min, args[0]);

console.log(min(1, 3, 4, 5, 6, 0.5, 4, 10, 5.5));
console.log(min(12, 5));

CodePudding user response:

You can try this

function getMin(a,b) {
  var min = arguments[0];
   for (var i = 0, j = arguments.length; i < j; i  ){
        if (arguments[i] < min) {
             min = arguments[i];
         }
    }
  return min;
}

console.log(getMin(-6.5,4));

CodePudding user response:

const min = (a, b) => {
 let arr = [a, b];
 return arr.sort((a, b) => a - b)[0];
};

console.log(min(4.5, 5)); // 4.5

this min() function sorts the array and returns the first element. this should return the smallest element. example:
min([2, 3]) -> 2
min([4.5, 9]) -> 4.5

  • Related