$(document).ready(function() {
function getWords() {
var wordsSet = $('.array-code li span'),
wordsArray = [];
$.each(wordsSet, function(index, value) {
wordsArray[index] = $(value).text();
});
return wordsArray;
}
function findTheLongestWord(array) {
var maxWordLength = 0,
longestWordIndex = 0;
array.forEach(function(element, index, array) {
if (element.length > maxWordLength) {
maxWordLength = element.length;
longestWordIndex = index;
}
});
return {
word: array[longestWordIndex],
position: longestWordIndex,
wordLength: array[longestWordIndex].length
};
}
function printTheLongestWord(wordObject) {
var longestWord = document.querySelector('.longest-word'),
longestWordIndex = document.querySelector('.longest-word-index'),
longestWordLength = document.querySelector('.longest-word-length');
longestWord.innerHTML = wordObject.word;
longestWordIndex.innerHTML = wordObject.position;
longestWordLength.innerHTML = wordObject.wordLength;
}
printTheLongestWord(findTheLongestWord(getWords()));
$('ul.array-code').on('click', 'span', function() {
var parent = $(this).parent(),
oldWord = $(this).text();
$('input').hide();
$('input').parent().find('span').show();
$(this).hide();
parent.find('input').show().val(oldWord).focus();
$('button.new-word').attr('disabled', 'disabled');
});
$('ul.array-code').on('keydown', 'input', function(event) {
var key = event.which,
parent = $(this).parent(),
newWord,
nextElement = parent.next(),
previousElement = parent.prev(),
previousElementText = previousElement.find('span').text();
if (key === 27) {
if ($(this).hasClass('new-word')) {
parent.remove();
} else {
$(this).hide();
parent.find('span').show();
}
$('button.new-word').removeAttr('disabled');
}
if (key === 13) {
newWord = $(this).val();
if (!newWord) {
parent.remove();
if (!nextElement.html()) {
previousElement.empty();
previousElement.append('\'<span>' + previousElementText + '</span><input type="text">\'');
$('button.new-word').removeAttr('disabled');
}
} else if ($(this).hasClass('new-word')) {
previousElement.html(previousElement.html() + ',');
$('button.new-word').removeAttr('disabled');
}
$(this).removeClass('new-word').hide();
parent.find('span').removeClass('new-word').show().text(newWord);
$('button.new-word').removeAttr('disabled');
printTheLongestWord(findTheLongestWord(getWords()));
}
});
$('button.new-word').click(function() {
$('ul.array-code').append('<li>\'<span class="new-word"></span><input class="new-word" placeholder="Enter new word">\'</li>');
$('input.new-word').show().focus();
$(this).attr('disabled', 'disabled');
});
$('button.clear-words').click(function() {
$('ul.array-code').empty();
});
});