Skip to content

Instantly share code, notes, and snippets.

@humphd
Created May 16, 2019 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humphd/a78aa6b29935df0cc247776c9955aa41 to your computer and use it in GitHub Desktop.
Save humphd/a78aa6b29935df0cc247776c9955aa41 to your computer and use it in GitHub Desktop.
WEB422 Summer 2019 Week 2 Code Example: jQuery, Lodash, Moment
<div id="employee-tables"></div>
<script src="index.js"></script>
// Import all the necessary modules we'll use,
// picking only the bits we care about vs. the entire thing.
const {
map,
pick,
forEach,
filter,
chunk,
shuffle
} = require('lodash');
const $ = require('jquery');
const moment = require('moment');
/**
* Given an Array of Tables (Arrays of 5 Employees per Table), format
* them into the following HTML and display:
*
* <div>
* <h2>Table 1</h2>
* <ul>
* <li>FirstName LastName</li>
* ...
* </ul>
* </div>
*/
const displayTables = tables => {
forEach(tables, function(table, index) {
const tableDiv = $(`<div><h2>Table ${index + 1}</h2></div>`);
const ul = $('<ul></ul>');
forEach(table, function(employee) {
const li = $(`<li>${employee.FirstName} ${employee.LastName} (${employee.yearsWorked})</li>`);
ul.append(li);
});
tableDiv.append(ul);
$('#employee-tables').append(tableDiv);
});
};
/**
* Given all employees, calculate how long each has been working for the
* company, filter the list to find all who have 8 or more years of
* service, shuffle that array to randomize it, create tables of 5
* people for a seating plan at a dinner. Display each table
* in the web page.
*/
const generateTables = employees => {
const processedEmployees = map(employees, employee => {
const modifiedEmployee = pick(employee, ['FirstName', 'LastName', 'HireDate']);
const years = moment().diff(employee.HireDate, 'years');
modifiedEmployee.yearsWorked = years;
return modifiedEmployee;
});
const eightOrMore = filter(processedEmployees, employee => employee.yearsWorked >= 8);
const shuffled = shuffle(eightOrMore);
const tables = chunk(shuffled, 5);
return tables;
}
// Get all Employees from our web service using jQuery's ajax() function
$(() => {
$.ajax({
// Swap this for your own
url: 'https://quiet-wave-16481.herokuapp.com/employees',
// Define our data type to be JSON, so it will get parsed for us
dataType: 'json'
})
.done(employees => {
const tables = generateTables(employees);
displayTables(tables);
})
.fail(function() {
console.log('it failed');
});
});
{
"name": "employee-tables",
"version": "1.0.0",
"scripts": {
"build": "parcel index.html"
},
"dependencies": {
"jquery": "^3.4.1",
"lodash": "^4.17.11",
"moment": "^2.24.0"
},
"devDependencies": {
"parcel": "^1.12.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment