Sections of story - like goto in notepad


#1

For a school project, i am creating a text based game in JavaScript.
I have a section at the start where you choose your name. I would like to make it so that if you choose certain names, it will give you different story output than normal. Is there a way i could do this without a large switch or if statement?

Thanks


#2

Mapping (associating) keys to values is incredibly common, in fact that's what variables in js are.
If your story is a value (for example a string, or perhaps a function) then map the name to such a story:

function cinderellaStory() {
  console.log('Once upon a time...');
}

var dispatch = {
  cinderella: cinderellaStory
};

dispatch['cinderella']();  // prints Once upon a time...
dispatch.hasOwnProperty('bob');  // false
dispatch.hasOwnProperty('cinderella');  // true

If you're using a recent js version then Map would be a better data structure than regular objects (avoids language internals, attributes that are already defined):

var dispatch = new Map();
dispatch.set('cinderella', cinderellaStory);
dispatch.has('cinderella');  // true
dispatch.get('cinderella')();  // prints Once upon a time...

If each part of the story is a function, then you might let each part call the next, alternatively return the next function so that you can call it in a loop if you wish to avoid a deep call-stack but that's probably not a problem in your case