Created
December 26, 2016 23:05
-
-
Save m-x-k/1f1078c88488d4b6a04702366761f5c9 to your computer and use it in GitHub Desktop.
ChatBot with module design pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="keywords" content="design patterns"> | |
<title>Mastering Javascript</title> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> | |
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> | |
<script src="moduleDesignPattern.js"></script> | |
</head> | |
<body> | |
<h1>ChatBot</h1> | |
<h3>[Module Design Pattern]</h3> | |
<div class="container"> | |
<table class="advert table table-hover"> | |
</table> | |
<span id="talk"> | |
</span> | |
</div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chatModule = (function () { | |
var leadSelf = '<strong>ME:</strong> ', | |
leadComputer = '<strong>PC:</strong> ', | |
leadComputerQuote = '<strong>QUOTE:</strong> ', | |
aSaid = ["This is a Cyber Chat"], | |
msgYes = "Yes, that's a great idea." | |
msgNo = "No, that must be a mistake." | |
aQuote = ["Equations are the devil's sentences.", | |
"Be yourself; everyone else is already taken.", | |
"Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", | |
"I have not failed. I've just found 10,000 ways that won't work." | |
] | |
function echo(msg, style) { | |
aSaid.push("<tr class=\"" + style + "\"><td>" + msg + "</td></tr>"); | |
var aSaidLength = aSaid.length, | |
start = Math.max(aSaidLength - 6, 0), | |
out = ""; | |
for (var i=start; i<aSaidLength; i++) { | |
out += aSaid[i]; | |
} | |
$('.advert').html(out); | |
$('#talk span').text(msg); | |
} | |
return { | |
talk: function(msg){ | |
echo(leadSelf + msg, "success"); | |
}, | |
replayYesNo: function() { | |
var msg = Math.random()>.5 ? msgYes : msgNo; | |
echo(leadComputer + msg, "warning"); | |
}, | |
sayQuote: function() { | |
var msg = aQuote[Math.floor(Math.random()* aQuote.length)]; | |
echo("<small>" + leadComputerQuote + msg + "</small>", "info"); | |
} | |
}; | |
})(); | |
$(document).ready(function() { | |
chatModule.talk("this is great"); | |
chatModule.replayYesNo(); | |
chatModule.sayQuote(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment