Skip to content

Instantly share code, notes, and snippets.

@Michaela-Davis
Created March 12, 2017 03:26
Show Gist options
  • Save Michaela-Davis/faa7a738bb0ba0afad0ef080f022099c to your computer and use it in GitHub Desktop.
Save Michaela-Davis/faa7a738bb0ba0afad0ef080f022099c to your computer and use it in GitHub Desktop.
proper module pattern for node.js
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="js/pingpong.js"></script>
<script type="text/javascript" src="js/pingpong-interface.js"></script>
<title>Ping Pong</title>
</head>
<body>
<form id="ping-pong-form">
<label for="goal">Enter a number:</label>
<input id="goal" type="number">
<button type="submit">Submit</button>
</form>
<ul id="solution"></ul>
</body>
</html>
var myModule = require('./pingpong.js');
$(document).ready(function() {
$('#ping-pong-form').submit(function(event) {
event.preventDefault();
var goal = $('#goal').val();
var output = myModule.pingityPongity(goal);
output.forEach(function(element) {
$('#solution').append("<li>" + element + "</li>");
});
});
});
module.exports = (function(){
function pingPong(goal) {
var output = [];
for (var i = 1; i <= goal; i++) {
if (i % 15 === 0) {
output.push("ping-pong");
} else if (i % 5 === 0) {
output.push("pong");
} else if (i % 3 === 0) {
output.push("ping");
} else {
output.push(i);
}
}
return output;
}
return {
pingityPongity: pingPong // this is exposed to the outside because it's a returned key-value pair
};
}());
// https://toddmotto.com/mastering-the-module-pattern/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment