0

I have a kinda strange task: create a function that creates other functions (and they will wrap text in HTML tags).

The problem is I can't figure out how to pass parent arguments in child function.

function wrapperBuild(tag) {
  return new Function('text', "return '<' + tag + '>' + text + '<' + tag + '/>");
};

let wrapP = wrapperBuild("p");

console.log(wrapP('some text'));

//expected output: <p>some text</p>
Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24

2 Answers2

3

There are multiple ways to call it.

And also you should use Template literals rather than joining strings.


1

function wrapperBuild(tag) {
  return function (text) {
    return `<${tag}>${text}</${tag}>`;
  };
}

let wrapP = wrapperBuild("p");

console.log(wrapP("some text"));

2

function wrapperBuild(tag) {
  return function (text) {
    return `<${tag}>${text}</${tag}>`;
  };
}
let p = wrapperBuild("p")("some text");

console.log(p);

// OR - console.log(wrapperBuild("p")("some text"));

3

You can simplify it more by using arrow functions...

const wrapperBuild = (tag) => (text) => `<${tag}>${text}</${tag}>`;

console.log(wrapperBuild("p")("some text"));



Some useful links:


Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
0

Try to return a new function that takes text and returns html. I've used arrow function

Using arrow function

function wrapperBuild(tag) {
  return (text) => {
    return `<${tag}> ${text} </${tag}>`;
  };
}

const fn = wrapperBuild("h1");
console.log(fn("hello world"));

Using old school function

function wrapperBuild(tag) {
  return function(text){
    return `<${tag}> ${text} </${tag}>`;
  };
}

const fn = wrapperBuild("h1");
console.log(fn("hello world"));
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • it works, but im confused with syntax tho :) – Johny1995QQ Mar 28 '21 at 17:06
  • @Johny1995QQ I'm doing exactly what you're doing like returning a function(arrow function in this case), which accepts an argument `text`. So this function `fn` will run and print the result. But you must be wondering about tag, Where does it come. It would come from `closure` – DecPK Mar 28 '21 at 17:12