'use strict';

var markovDictionaryBuilder = (function() {

	function buildDict(wordSet, chainSize) {
		console.log("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize);

		var dict = [];
		for (var i = 0, len = wordSet.length - chainSize; i < len; i++) {
			
			var end = i + parseFloat(chainSize); 
			var workingSet = wordSet.slice(i, end+1);
			var k = workingSet.slice(0, workingSet.length-1);
			var n = [workingSet.slice(-1)];
			
			var dictItem = {
				'key' : k.join('/').toLowerCase(),
				'words' : k,
				'next' : n
			};
			
			var match = getDictItemByKey(dict, dictItem.key);
		  
			if (match !== null) {
				var index = dict.indexOf(match);
				dict[index].next.push(dictItem.next[0]);
			} else {
				dict.push(dictItem);
			}
		}
		//console.log(dict);
		return dict;
	}

	function getDictItemByKey(dict, key) {
		for (var i = 0, len = dict.length; i < len; i++) {
			if (dict[i].key === key) return dict[i];
		}
		return null;
	}

	return { buildDict : buildDict  };

})();
'use strict';

var markovDictionaryBuilder = (function() {

	function buildDict(wordSet, chainSize) {

		console.log("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize);

		var map = [];
		var dict = [];
		for (var i = 0, len = wordSet.length - chainSize; i < len; i++) {
			
			var end = i + parseFloat(chainSize); 
			var workingSet = wordSet.slice(i, end+1);
			var k = workingSet.slice(0, workingSet.length-1);
			var n = workingSet.slice(-1);
			
			var dictItem = {
				'key' : k.join('/').toLowerCase(),
				'words' : k,
				'next' : n
			};
			
			var mi = map[dictItem.key];
			if (typeof(mi) === 'undefined') {
				map[dictItem.key] = dict.length;
				dict.push(dictItem);
			} else {
				dict[mi].next.push(dictItem.next[0]);
			}
		}
		return dict;
	}

	return { 
		buildDict : buildDict
	};

})();
Store the dictItem keys in a map to avoid searching the dict for objects with matching keys (this cut performance tests from 5000ms to 150ms)