Reactiflux
Reactiflux

help-js

Root Question Message

ekomS
ekomS12/21/2022
I have an object with nested functions, like so:
const arrayFunctions = {
  f1: (a)=> {},
  f2: (a,b)=> {},
  f3: {
    test: (a)=>{}
  }
} 

Is there any way I can specify default behavior if just arrayFunctions is called? Example:
let a = arrayFunctions.f1([1,2]);
let b = arrayFunctions([4,3,2]);
ScriptyChris
ScriptyChris12/22/2022
@180042828733218816 arrayFunctions is not a function, so you can't call it. You can make it a function and then attach properties to it
ScriptyChris
ScriptyChris12/22/2022
const arrayFunctions = () => { /* do some stuff */ };
arrayFunctions.f1 = (a)=> {};
arrayFunctions.f2 = (a,b)=> {};
arrayFunctions.f3 = {
  test: (a)=>{}
};
ekomS
ekomS12/22/2022
Is there any way to nest this assignment within the arrayFunctions function?
ekomS
ekomS12/22/2022
So that I don't need to write a new line for every deeply nested method
ScriptyChris
ScriptyChris12/22/2022
No, because you first have to declare a function (which is a special kind of object in JavaScript) and then mutate it by adding properties
ScriptyChris
ScriptyChris12/22/2022
Though you could have a group of props, which you could define as a single object
ScriptyChris
ScriptyChris12/22/2022
const subFunctions = {
  f1: (a)=> {},
  f2: (a,b)=> {},
  f3: {
    test: (a)=>{}
  },
}
const arrayFunctions = () => { /* do some stuff */ };
arrayFunctions.subFunctions = subFunctions;
ekomS
ekomS12/22/2022
  turnObjectIntoFunction(object, options) {
    let temp = object._default
      ? function (args) {
          return object._default(args);
        }
      : {};

    let keys = Object.keys(object);

    for (let index = 0; index < keys.length; index++) {
      let key = keys[index];
      let data = object[key];

      if (key !== '_default')
        temp[key] =
          typeof data == 'object' && !Array.isArray(data) && options?.recursive
            ? this.turnObjectIntoFunction(data)
            : data;
    }

    return temp;
  },
ekomS
ekomS12/22/2022
I figured something out
ekomS
ekomS12/22/2022
This seems to work
ekomS
ekomS12/22/2022
I just give my desired default behavior the _default key
ekomS
ekomS12/22/2022
And then parse the object through turnObjectIntoFunction before I export my function/object
ekomS
ekomS12/22/2022
Fobject?
ekomS
ekomS12/22/2022
There's probably plenty of ways to optimize but I'm quite possibly braindead after two hours of monkeying around with it
ScriptyChris
ScriptyChris12/22/2022
I think you overcomplicated this, because it's easier to create an object and append it as function's prop than making some recursion stuff 😛
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy