ninesalt
ninesalt

Reputation: 4354

High level prototype functions

I'm trying to create a wrapper in nodejs that abstracts different functions depending on the input of the main wrapper. So for example, lets say I have two different files, one called usa and one called uk and they both have the same functions, but they have different functionalities. I'm trying to have write a function, that given either the string us or uk, I get a wrapper function that I can call like this:

const Wrapper = MyWrapper('uk')
const func1Output = Wrapper.func1(10)

I currently have the above working, the uk file just defines the functions inside it as prototypes as follows:

function MyWrapper () { }
MyWrapper.prototype.func1 =  (input) => console.log(input)
return new MyWrapper()

This is working fine. My current situation is that there are lots of functions across different files that should be accessible by the wrapper. Its not just func and whatever else is in that specific file. This is my folder structure

wrappers
 - feed
  -- uk
  -- us
 - news
  -- uk
  -- us

//etc

Where each file titled uk/us has the prototype functions like in the second code snippet. So whenever I want to use the feed module for example, I have to do like in the first code snippet. So its a per-module prototype, its not high level where it would be per string (ie uk/us).

What I'm trying to do is have just one file, index.js in my wrappers folder which is responsible for giving me one wrapper for all of the modules. Something like MyWrapper('uk').feed.func1()

This is kind of a hard question to explain but I'd be happy to edit the post for more clarification if needed.

Upvotes: 0

Views: 29

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138437

Why not just return regular objects ?

 // wrapper/index.js
 const wrappers = {
  uk: {
   func1() { /*...*/ }
  },

  us: {
   func1() { /*...*/ }
  }
};

module.exports = country => wrappers[country];

That can be used as:

  const wrapper = require("./wrapper/")("uk");
 wrapper.func1();

Upvotes: 1

Related Questions