JSFiddle - React, Tailwind, and code Playground

by wrxsti85

HTML

<div id="responses"></div>
<form id="interface">
	<input type="text" name="user-input" />
	<button type="submit">Send</button>
</form>

CSS

#responses {
	height: 200px;
	overflow-y: scroll;
}

JavaScript

function Bot(nm){
	var name = nm,
		responses = {},
		botStatement = null;
		
	this.dunno = function(statement){
		var keys = Object.keys(responses);
		var possibleDiff = responses[keys[ keys.length * Math.random() << 0]];
		if(possibleDiff != null){
			return possibleDiff[Math.floor(Math.random() * possibleDiff.length)];
		} else {
			return "I don't know how to respond to that yet...";
		}
	};
	
	this.sanitize = function(statement){
		return statement.toLowerCase().replace(/[^a-zA-Z ]/g, "");
	};
	
	this.processStatement = function(statement){
		statement = this.sanitize(statement);
		this.dynamicLibrary(statement);
		var res = Object.keys(responses).indexOf(statement);
		return  res > -1 ? responses[statement][Math.floor(Math.random() * responses[statement].length)] : this.dunno(statement);
	};
	
	this.dynamicLibrary = function(statement){
		if(typeof responses[botStatement] === 'undefined'){
			responses[botStatement] = [];
		}
		if(responses[botStatement].indexOf(statement) < 0){
			responses[botStatement].push(statement);
		}
		console.log(responses);
	};
	
	this.greeting = function(){
		botStatement = "hello";
		return "Hello...My name is " + name;
	};
	
	this.output = function(output, you){
		botStatement = output;
		if(you != null){
			$('#responses').append('<p>You: ' + you + '</p>');
		} 
		$('#responses').append('<p>' + name + ": " + botStatement + '</p>');
		$('#responses').animate({scrollTop: $('#responses').prop('scrollHeight')});
	};
	
	this.output(this.greeting());
	
}

$(function(){

	var bot = new Bot("Rawr Guthlaf");

	$('form').on('submit', function(e){
		e.preventDefault();
		var data = $(this).serializeArray();
		bot.output(bot.processStatement(data[0].value), data[0].value);
		$(this)[0].reset();
	});
	
});