Reputation: 19
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
Reputation: 3921
There are multiple ways to call it.
And also you should use Template literals rather than joining strings.
function wrapperBuild(tag) {
return function (text) {
return `<${tag}>${text}</${tag}>`;
};
}
let wrapP = wrapperBuild("p");
console.log(wrapP("some text"));
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"));
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
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