Skip to content Skip to sidebar Skip to footer

Combine These Specific Javascript Functions

I have these two separate javascript functions that perform the same task using either numbers or white space. I'm not all that familiar with functions so my question is how would

Solution 1:

The only difference is the concatenated value. You can create a function to concatenate a return value.

function pad(string, length, fn) {
  while (string.length < length) {
    string += typeof fn === 'string' ? fn : fn();
  }
  return string;
}

const padnum = (str, len) => pad(str, len, () => Math.floor(Math.random() * 10));
const ws     = (str, len) => pad(str, len, " ");

console.log(padnum('00', 5));
console.log(ws('Hello', 8));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Solution 2:

You can pass a parameter to function to return value which meets condition

function padnum(string, len, type) {
  while (string.length < len) {
    string += type === "randomPad" ? Math.floor(Math.random() * 10) : " ";
  }
  return string;
}

var len = 5;

var spaces = 2;

var res = padnum(padnum("abc", len, "randomPad"), len + spaces);

console.log(res, res.length);

Post a Comment for "Combine These Specific Javascript Functions"