Johny1995QQ
Johny1995QQ

Reputation: 19

How to pass argument from parent function to child function

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>

Upvotes: 0

Views: 1056

Answers (2)

Manas Khandelwal
Manas Khandelwal

Reputation: 3921

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:


Upvotes: 3

DecPK
DecPK

Reputation: 25408

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"));

Upvotes: 0

Related Questions