JSFiddle - React, Tailwind, and code Playground
Clipnow Frontend developer test
by DIdac Montero
HTML
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<form>
<button type='button' id="add_row" href="javascript:void(0);">
Add row
</button>
<table style="width:100%">
<tr>
<th>ID</th>
<th>Price</th>
<th>Description</th>
<th>Delete</th>
</tr>
</table>
<button type='button' id="submit" href="javascript:void(0);">
submit
</button>
</form>
<div class="row template" style="display: none;">
<input class="required" type="number" name="id">
<input class="required" type="number" name="price">
<input type="text" name="description">
<button type='button' class="removeRow">
Remove row
</button>
</div>
CSS
th {
border: 1px solid black;
}
td {
padding-right: 4px;
}
input {
width: 100%;
margin-right: 5px;
}
JavaScript
var Row = function(id, price, description) {
this.id = parseFloat(id);
this.price = parseFloat(price);
this.description = description;
};
$("#add_row").click(function() {
var row = $(".row.template").clone();
var html = "";
row.find("input, button").each(function() {
html += "<td>" + this.outerHTML + "</td>";
});
$("table").append("<tr class='row'>" + html + "</tr>").find(".removeRow").click(function() {
$(this).parent().parent().remove();
});;
});
$("#submit").click(function(e) {
var allFieldsChecked = true;
$('form input.required').each(function() {
if (!$(this).val() ||
$(this).prop("name").indexOf("id") > -1 && !isNumber($(this).val()) ||
$(this).prop("name").indexOf("price") > -1 && !(parseFloat($(this).val()) && $(this).val().match('^-?[0-9]*\.[0-9]*$'))) {
alert('Some fields are empty == ' + $(this).val());
allFieldsChecked = false;
return false;
}
});
if (allFieldsChecked) {
var elemns = fromFormToObject($("form"));
// Deep copy
var elemnsCopy = JSON.parse(JSON.stringify(elemns));
console.log("Sort by ID (descending):");
console.log(elemnsCopy.sort(compareId));
console.log("Sort by price (descending)");
var elemnsCopy2 = JSON.parse(JSON.stringify(elemns));
console.log(elemnsCopy2.sort(comparePrice));
console.log("cut descriptions to 3 sentences");
var elemnsCopy3 = JSON.parse(JSON.stringify(elemns));
for (i = 0; i < elemnsCopy3.length; i++) {
var elem = elemnsCopy3[i];
if (elem.description) {
elem.description = elem.description.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|", 3).join(" ");
}
}
console.log(elemnsCopy3);
}
});
function fromFormToObject(form) {
var elemns = [];
form.find("tr.row").each(function() {
var elem = $(this);
var row = new Row(
elem.find("input[name='id']").val(),
elem.find("input[name='price']").val(),
...