This is more to get clarity on an implementation that I did. I am working on a React, Node, and Electron application that essentially has a form that a user inputs values that will update some content files.

The application has to scale for a lot of different scenarios so I found that I kept writing switch statements to incorporate all of these scenarios. So for the sake of time I wrote a class that:

  1. Takes in two arrays, An array of keys and array of functions that correspond to those keys.
  2. The constructor function creates a table for the values
  3. Then there is a method on the class that allows you to look up that value and returns it

here is the code

Array.prototype.createObjectFromKeysandValues = function(array) {
    let table = {}
    for(let pointer=0;pointer<this.length;pointer++){
        let key = this[pointer]
        let value = array[pointer]
    return table

  module.exports = class KeyFunctionMappingTable {
      constructor(keys, values){
        this.lookUpTable = Object.assign({},
         { default: () =>  new Error("Value Not Found")})

        return this.lookUpTable[value]|| this.lookUpTable.default

So when the code is implemented it looks like this ( this scenario is for React Components) :

const factory = new KeyFunctionMappingTable(['select', 'input'], [
    (options, labelText) => ( <Select options={options} labelText={labelText} />),
    (options, labelText) => ( <Input labelText={labelText} />)])

I am finding that I have about three of these "mappings" throughout the code.

What I want to know is if this seems like a readable implementation and does this make sense to strangers. If you dont think so please let me know your suggestion.


1 Answer 1


You have just added an unneeded layer of complexity to the problem.

You can just create the factory as an Object

const factory = {
    select(opts, text) { return (<select options={opts} labelText={text} />) },
    input(opts, text) { return (<input labelText={text} />) },
    default() { return new Error("Value Not Found") }

Then call the function with

(factory[value] || factory.default)(opts, text);
  • \$\begingroup\$ Hey thanks for this. Should I keep the class or just use objects through out the application in all of the instances of this? \$\endgroup\$ Commented Dec 25, 2019 at 2:21
  • 1
    \$\begingroup\$ @GrantHerman Keep it simple and just use the object where you previously assigned KeyFunctionMappingTable \$\endgroup\$
    – Blindman67
    Commented Dec 25, 2019 at 3:44
  • \$\begingroup\$ You may also want to add method that encpsulates the invocation with fallback to default, so that the || factory.default invocation does not get repeated. \$\endgroup\$
    – slepic
    Commented Dec 25, 2019 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.