Revealing pattern
by John Wick
JavaScript
var chatModule = (function() {
// Private variables/methods prefix with _
var _leadself = 'Hello...',
_leadcomputer = 'PC ',
_aSaid = ['This is cyber chat'],
_msgYes = 'Yes, thats a great idea',
_msgNo = 'No, that must be a mistake',
_aSassyStuff = ['the quick brown fox', 'lorem ipsum dolor sit amet', 'jump over the lazy dog'];
function _echo(msg) {
_aSaid.push(msg);
var aSaidLength = _aSaid.length,
start = Math.max(aSaidLength.length - 3, 0),
out = '';
for(var i=start; i < aSaidLength; i++) {
out += _aSaid[i];
}
console.log('out:', out);
console.log('msg:', msg);
}
function talk(msg) {
_echo(_leadself + msg);
}
function replyYesNo() {
var msg = Math.random() > 5 ? _msgYes: _msgNo;
_echo(_leadcomputer + msg);
}
function aSassyStuff() {
var msg = _aSassyStuff[Math.floor(Math.random() * _aSassyStuff.length)];
_echo(_leadcomputer + msg);
}
// return Public functions
return {
talk: talk,
replyYesNo: replyYesNo,
aSassyStuff: aSassyStuff
}
})();
//console.log('1:', chatModule.echo); //nothing will return
//console.log('2:', echo); //echo is not defined
console.log(' ');
chatModule.talk('this is awesome!');
chatModule.replyYesNo();
chatModule.aSassyStuff();