Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ES6 Destructuring
- // lots of duplicate code can be saved with destructuring
- // ES5
- var expense = {
- type: 'Business',
- amount: '$45 USD'
- };
- var type = expense.type;
- var amount = expense.amount;
- // ES6
- const { type } = expense
- const { amount } = expense
- // even shorter
- const { type, amount } = expense
- // creates expense.type and expense.amount
- // Destructuring Arguments Object
- var savedFile = {
- extension: 'jpg',
- name: 'repost',
- size: 14040
- };
- // ES5
- // object represents file on hdd
- function fileSummary(file) {
- return `The file ${file.name}.${file.extension} is of size ${file.size}`;
- }
- fileSummary(savedFile);
- // ES6
- function fileSummaryES6( { name, extension, size } ) {
- return `The file ${name}.${extension} is of size ${size}`;
- }
- fileSummaryES6(savedFile);
- // ES6 destructuring with a second argument
- function fileSummaryExtES6( { name, extension, size }, { color } ) {
- return `The file ${name}.${extension} is of size ${size} and ${color} as color`;
- }
- fileSummaryExtES6(savedFile, { color: 'red'});
- // Destructuring Arrays
- // destructuring an array is pulling off individual elements
- const companies = [
- 'Google',
- 'Facebook',
- 'Uber'
- ]
- const [ name, name2, name3 ] = companies;
- name //returns Google
- // destructure a property with the curly braces
- const { length } = companies;
- length // returns 3
- // destructure
- const [ firstCompany ] = companies;
- const [ lastCompany ] = companies;
- firstCompany // returns "Google"
- lastCompany // returns "Google"
- // in combination with the rest operator
- const [ companyName, ...rest ] = companies
- companyName // returns "Google"
- rest // returns ["Facebook", "Uber"]
- // Destructuring Arrays and Objects at the same time
- const companies = [
- { name: 'Google', location: 'Mountain View'},
- { name: 'facebook', location: 'Menlo Park'},
- { name: 'Uber', location: 'San Fransisco'}
- ]
- // ES5
- const location = companies[0].location;
- // ES6
- // outside to the inside
- const [{ location }] = companies
- // walking direction to destructuring
- const Google = {
- locations: ['Mountain View', 'New York', 'London']
- }
- // look at the 'locations' property
- // returns array
- // take out array
- // pull out first element
- const { locations: [ location ] } = Google;
- // returns Mountain View
- // ARGUMENTS
- // good use for destructuring arguments
- function signup(username, password) {
- // create new user
- }
- signup('Boris','sd78aHg3')
- // later on you extend the function
- function signup(username, password, email, dateOfBirth, city) {
- // create new user
- }
- // it is dangerous because the order of the parameters can change!
- // like here on purpose
- signup('Boris','sd78aHg3', '1/1/1983', 'boris@boo.com', 'New York')
- // instead of a list of strings
- // use a object
- const user = {
- username: 'Boris',
- password: 'sd78aHg3',
- email: 'boris@boo.com',
- dateOfBirth: '1/1/1983',
- city: 'New York'
- }
- // now the order is no problem because we destrucuted them
- function signup({username, password, email, dateOfBirth, city}) {
- // create new user
- }
- signup(user);
- // ARRAY
- // good use for destructuring arrays
- const points = [
- [4, 5],
- [10, 1],
- [0, 40]
- ]
- // what we want to get out of these nester arrays
- [
- { x: 4, y: 5 },
- { x: 10, y: 1 },
- { x: 0, y: 40 },
- ]
- // map over the list wioth all the points
- points.map(([ x, y ]) => {
- // and return the points in objects
- return { x: x, y: y }
- // improved object literals
- return { x, y }
- })
- // QUIZ ONE
- // The snippet of code below duplicates references to 'profile' inside of the 'isEngineer' function. Perhaps we can reduce the amount of code used for referencing the 'title' and 'department' properties. Refactor this code to use destructuring. Can you get the body of the 'isEngineer' function down to a single line?
- const profile = {
- title: 'Engineer',
- department: 'Engineering'
- };
- function isEngineer(profile) {
- var title = profile.title;
- var department = profile.department;
- return title === 'Engineer' && department === 'Engineering';
- }
- // change the arguments to make the fn a one liner
- function isEngineer({title, department}) {
- return title === 'Engineer' && department === 'Engineering';
- }
- // QUIZ TWO
- // The 'classes' variable holds an array of arrays, where each array represents a single class that a student is enrolled in. Convert this array of arrays into an array of objects, where each object has the keys 'subject', 'time', and 'teacher' and assign the result to 'classesAsObject. Use array destructuring and the map helper.
- // An array for a class has the form [subject, time, teacher]
- // The resulting data structure should look something like the following:
- //
- // const classesAsObject = [{ subject: 'Geography', time: '2PM', teacher: 'Mrs. Larsen' }]
- const classes = [
- [ 'Chemistry', '9AM', 'Mr. Darnick' ],
- [ 'Physics', '10:15AM', 'Mrs. Lithun'],
- [ 'Math', '11:30AM', 'Mrs. Vitalis' ]
- ];
- const classesAsObject;
- // es6 map destructor
- const classesAsObject = classes.map(([subject, time, teacher]) => {
- return { subject, time, teacher }
- });
- // QUIZ THREE Recursion with Destructuring
- // Use array destructuring, recursion, and the rest/spread operators to create a function 'double' that will return a new array with all values inside of it multiplied by two. Do not use any array helpers! Sure, the map, forEach, or reduce helpers would make this extremely easy but give it a shot the hard way anyways :)
- // Input:
- // double([1,2,3])
- //
- // Output
- // [2,4,6]
- //
- // Hint: Don't forget that with recursion you must add a base case so you don't get an infinite call stack. For example, if 'const [ number, ...rest ] = numbers' and number is undefined do you need to keep walking through the array?
- const numbers = [1, 2, 3];
- // solution 1
- const double = ([num, ...rest]) =>
- rest.length?
- [ num *2, ...double(rest) ] : [ num * 2 ];
- double(numbers);
- // solution 2
- const doubledNumbers = numbers.map(number => {
- return number * 2;
- });
Add Comment
Please, Sign In to add comment