I am looking to create a function that combines an object, a path in a variable, and another path, similar to what is described in this StackOverflow post, but with 3 different components.
Here is a simple example to illustrate my goal:
I want the combine()
function to output either
selector[0].children[foo].textContent
or selector[0].children[foo].children[0].textContent
based on the value of the bar
variable.
const selector = document.getElementsByClassName('main')
const foo = 0
let bar = ''
const toggle = () => {
if (bar === '') bar = '.children[0]'
else bar = ''
}
const test = () => {
console.log(combine('selector[0].children[foo]', bar, '.textContent'))
}
<div class='main'>
<h1>Hello<span>world</span></h1>
<button onclick='toggle()'>toggle</button>
<button onclick='test()'>test</button>
</div>
I have a class that returns multiple properties (10) that are similar. The constructor takes a value that can determine something akin to the bar
variable in the example above. By simply adjusting this value, each property can produce the desired result.
I am seeking a solution that allows for switching between different scenarios without the need for extensive switch cases to handle each situation separately, thus reducing code duplication.