0

I am trying to create a random name generator which takes its first and last names from separate files. Which is the easiest way to do so while keeping the resource files easily modifiable?

Thanks for your help!

Edit:

//---------------------first js-file humanVillages.js

var nameSyllables = ["aber", "ac", "acc", "ock", "afon", "avon", "ar", "ard"];

function CreateNewHumanName()
{
    //Creates a first name with 1-3 syllables
    var firstName = "";
    var numberOfSyllablesInFirstName = Math.floor(getRandom(2, 5));
    for (var i = 0; i < numberOfSyllablesInFirstName; i++)
    {
        firstName += nameSyllables[Math.floor(getRandom(0, (nameSyllables.length + 1)))]; 
    }
 
    var firstNameLetter = firstName[0];
    firstName = firstName.slice(1);
    firstNameLetter = firstNameLetter.toUpperCase();
    firstName = firstNameLetter + firstName;

    //Creates a second name with 2-4 syllables
    var secondName = "";
    var numberOfSyllablesInSecondName = Math.floor(getRandom(4, 6));
    for (var i = 0; i < numberOfSyllablesInSecondName; i++)
    {
        secondName += nameSyllables[Math.floor(getRandom(0, (nameSyllables.length + 1)))];
    }

    var secondNameLetter = secondName[0];
    secondName = secondName.slice(1);
    secondNameLetter = secondNameLetter.toUpperCase();
    secondName = secondNameLetter + secondName;

   // var completeName = firstName + " " + secondName;
    var completeName = firstName;
    return completeName;
}



//-------------second js file scripts.js

// Declare the Object of Village, with name, 
// number of villagers and array of villager objects 
function Village(villageName, villagersAmount, villagersList, villageSizeDescriptor) {
  this.villageName = villageName;
  this.villagersAmount = villagersAmount;
  this.villagersList = villagersList;
  this.villageSizeDescriptor = villageSizeDescriptor;
};

Village.prototype.villageName = function() {
  return this.villageName;
};
Village.prototype.villagersAmount = function() {
  return this.villagersAmount;
};
Village.prototype.villagersList = function() {
  return this.villagersList;
};
Village.prototype.villageSize = function() {
  return this.villageSize;
};
console.log("Village created correctly");


// Declare the Object of Villager, with preset first_name, 
function Villager(firstName) {
  this.firstName = firstName;
};
Villager.prototype.firstName = function() {
  return this.firstName;
};
console.log("Villager created correctly");

// Random Number Generator for incremental village size choices
function getRandom(min, max) {
    return Math.random() * (max - min) + min;
};


$(document).ready(function() {
  $("form#create_village").submit(function(event) {
    event.preventDefault();
// Gather input for Village Creation
    var villageSizeInput = parseInt($("#size").val());
    var villagersAmount = 0;
    var villageSizeDescriptor = "";
// Use manual input for amount of villagers if selected and input is given
// Otherwise take villageSizeInput to switch to right random number range
    if (villageSizeInput == 0 && $("input#amount").val() == "") {
      alert("Please enter a value if you choose manual input!")
    } else if (villageSizeInput == 0 ) {
      villagersAmount = parseInt($("input#amount").val());
    } else if (villageSizeInput == 1){
      villagersAmount = Math.floor(getRandom(0, 50000));
    } else {
      switch (villageSizeInput) {
        case 2:
          villagersAmount = Math.floor(getRandom(0, 100));          
          break;
        case 3:
          villagersAmount = Math.floor(getRandom(100, 500));         
          break;
        case 4:
          villagersAmount = Math.floor(getRandom(500, 1000));          
          break;
        case 5:
          villagersAmount = Math.floor(getRandom(1000, 2000));
          break;
        case 6:
          villagersAmount = Math.floor(getRandom(1000, 5000));
          break;
        case 7:
          villagersAmount = Math.floor(getRandom(5000, 10000));
          break;
        case 8:
          villagersAmount = Math.floor(getRandom(10000, 25000));
          break;
        case 9:
          villagersAmount = Math.floor(getRandom(25000, 50000));          
          break;
      }
    }
// Take villagersAmount to set corresponding verbal size descriptor
    if (villagersAmount < 100)  {
      villageSizeDescriptor = "Thorp";
    } else if (villagersAmount < 500) {
      villageSizeDescriptor = "Hamlet";
    }else if (villagersAmount < 1000) {
      villageSizeDescriptor = "Village";
    }else if (villagersAmount < 2000) {
      villageSizeDescriptor = "Small Town";
    }else if (villagersAmount < 5000) {
      villageSizeDescriptor = "Large Town";
    }else if (villagersAmount < 10000) {
      villageSizeDescriptor = "Small City";
    }else if (villagersAmount < 25000) {
      villageSizeDescriptor = "Large City";
    }else {
      villageSizeDescriptor = "Metropolis";
    }
//create instance of Village and Villager
    //call on function in humanVillages.js to randomly create a villageName
    var newVillageName = CreateNewHumanName();
    var newVillage = new Village(newVillageName, villagersAmount, [], villageSizeDescriptor)
    var newVillager = new Villager("Bob");
// Create output of Village
    $("#villageType").text(newVillage.villageSizeDescriptor);
    $("#villagersAmount").text(newVillage.villagersAmount);
    $("#villageName").text(newVillage.newVillageName);
// Random creation of Villagers
    for (var index = 0; index < villagersAmount; index += 1) {
      newVillage.villagersList.push(newVillager.firstName);
      $("ul#villagers_names").append("<li><span class='villager'>" + newVillager.firstName + "</span></li>");
    }
// Reset manual Input Value
    $("input#amount").val("");
  });
});
<!DOCTYPE html>
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen" title="no title" charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="js/scripts.js"></script>
    <script src="resources/humanVillages.js"></script>
    <title>Village Creator 1.0</title>
 </head>
 <body>

  <div id="input">
   <!-- Selecting input for the village creation -->
   <h3>Create a village!</h3>
   <form id="create_village" onsubmit="return false;">
    <table>
     <tbody>
      <tr>
       <td>Select a town size</td>
              <td>
              <select id="size">
               <!-- Selecting town size by increment -->
         <option value="0"selected="">Manual</option>
         <option value="1">Any</option>
         <option value="2">Thorp</option>
         <option value="3">Hamlet</option>
         <option value="4">Village</option>
         <option value="5">Small Town</option>
         <option value="6">Large Town</option>
         <option value="7">Small City</option>
         <option value="8">Large City</option>
         <option value="9">Metropolis</option>
        </select>
       </td>
       <td>
        <!-- Selecting town size by specific numeric input -->
        <label for="amount">The amount of villagers: </label>
            <input type="number" name="amount" id="amount">
       </td>
      </tr>
      <tr>
       <td>Select a town name</td>
              <td>
              <select id="name">
               <!-- Selecting town name by random racial name -->
         <option value="0"selected="">Manual</option>
         <option value="1">Random Drarven</option>
         <option value="2">Random Elven</option>
         <option value="3">Random Gnome</option>
         <option value="4">Random Orc</option>
         <option value="5">Random Halfling</option>
         <option value="6">Random Human</option>
         <option value="7">Random Other</option>
        </select>
       </td>
       <td>
        <!-- Selecting town name by specific spelled input -->
        <label for="name">The name of the village: </label>
            <input type="text" name="name" id="name">
       </td>
      </tr>
      </tbody>
     </table>
       
       <button type="submit" class="btn btn-submit">Create!</button>
     </form>
  </div>

  <div id="output">
   <h3>Here there be a village!</h3>
   <!-- Output of village parameters -->
   <table>
    <tr>
     <th>Settlement Name</th>
     <td><span id="villageName"></span></td>
    </tr>
    <tr>
     <th>Settlement Type</th>
     <td><span id="villageType"></span></td>
    </tr><tr>
     <th>Population</th>
     <td><span id="villagersAmount"></span></td>
    </tr>
    <tr>
     <th>Villager Names</th>
     <td><ul id="villagers_names"></ul></td>
    </tr>
   </table>
  </div>
  
 </body>
</html>
lolcat
  • 119
  • 10
  • I seem to be doing everything right in calling the function and generating the data, i somehow am not able to export the data into a new variable – lolcat Jan 12 '16 at 00:00
  • checkout this tutorial http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/ . It will help you understand requirejs. It is very simple. – pro Jan 12 '16 at 01:31

1 Answers1

1

Checkout the require() function in node, it helps you access objects and functions that maybe on separate files.

file1: nums.js

var obj = {
    name: 'jack',
    age: 30
};

module.exports = obj; //exports the object

file2: app.js

var nums = require('./nums');

console.log(nums); // prints --> { name: 'jack', age: 30 }

UPDATED:

file1: nums.js

var  arr = [{
    name: 'jack',
    age: 30
    }, {
    name: 'a',
    age:40
    }, {
    name: 'abc',
    age:40
}];

module.exports = arr;

file2: app.js

var nums = require('./nums');

var rand = Math.floor(Math.random() * nums.length);

console.log(rand);
console.log(nums[rand]);
pro
  • 792
  • 7
  • 30
  • I am afraid the documentation is a good bit too complex for me to follow yet unaided... – lolcat Jan 11 '16 at 22:02
  • Although your answer is correct, I'm guessing by the technology used that the OP is creating a website, not a node.js service, so he might not be able to use `require()` – caulitomaz Jan 11 '16 at 22:08
  • Nice! So if i have a whole array of hashes and i randomly choose the exported object it in the nums.js, is the code run each time i require it in the app.js to produce a different result? Do i need other files added to my project to make this run? – lolcat Jan 11 '16 at 22:11
  • @lolcat If you are not using node.js you won't be able to use this answer. Your question must be clarified regarding technology used. – caulitomaz Jan 11 '16 at 22:12
  • I am indeed trying to create a website and have not yet used node.js. I have nothing against using it though, if the solution is proof against my lack of specific knowledge. – lolcat Jan 11 '16 at 22:13
  • An additional way of doing it that i found was this one: http://stackoverflow.com/questions/3809862/can-we-call-the-function-written-in-one-javascript-in-another-js-file Thanks for your help!! – lolcat Jan 11 '16 at 22:56
  • I seem to be doing everything right in calling the function and generating the data, i somehow am not able to export the data into a new variable – lolcat Jan 11 '16 at 23:43