dotdash's notebooks

  • Classes - /dotdash/classes
    Last edited 7 years ago
    // Write a class that represents a person. The class should take age, location, and name as inputs. The class should have methods to get each of these data points. // Solution class Person { constructor(age, location, name) { this.age = age; this.name = name; this.location = location; } getAge() { return this.age; } getLocation() { return this.location; } getName() { return this.name; } } ////////////////////////////////////////////////////////////////// // Write a class representing a database table/collection of persons. Your class should be able to allow the insertion, retrieving, updating, and deletion of persons. // Solution class PersonDatabase { constructor() { this.store = []; } delete(id) { this.store = this.store.filter((person) => person.id !== id); // Could be optimized } get(query) { return this.store.filter((person) => { for (let key in query) { if (!query.hasOwnProperty(key) || person[key] !== query[key]) { return false; } } return true; }) .slice(); } insert() { [...arguments].forEach((person) => { const id = date.now(); const personToStore = Object.assign({}, person, {id}); this.store.push(personToStore); }); } update(id, updates) { const personToUpdate = this.store.find((person) => person.id === id); const updatedPerson = Object.assign(personToUpdate, updates); return Object.assign({}, updatedPerson); } }
  • Promises - /dotdash/promises
    Last edited 7 years ago
    const Promise = require('bluebird'); const locations = ['Boston', 'Dallas', 'Houston', 'Miami', 'New York', 'San Francisco']; const names = ['Bob', 'John', 'Margaret', 'Tara']; function getPersonalInfo(key) { const random = Math.random(); const person = { age : Math.round(random * 100), location : Math.floor(random * locations.length), name : Math.floor(random * names.length), }; return Promise.resolve(person[key]); } // Using the above, write a function that returns a promise that resolves with `person` (an object representing a person's age, location, and name. Ignore the fact that we construct a person object with each invokation of getPersonalInfo. // Solution function getRandomPerson() { return Promise.join(getPersonalInfo('age'), getPersonalInfo('location'), getPersonalInfo('name')) .spread((age, location, name) => { age, location, name }); } ////////////////////////////////////////////////////////////////////// // Write a function that returns a promise that resolves around n second later after invoked with any value. // Solution 1 function getAfterNSeconds(n) { return new Promise((resolve) => setTimeout(() => resolve(), n)); } // Solution 2 function getAfterNSeconds(n) { return Promise.resolve().delay(n); } ////////////////////////////////////////////////////////////////////// const numbers = [1, 2, 3, 4, 5]; // Write a function that serially consumes the above data and multiplies each data point by n. The function should return a promise resolving with an array of the new values. // Solution function multiply(n) { return Promise.mapSeries(numbers, (number) => number * n); } ////////////////////////////////////////////////////////////////////// const multipliers = [2, 4, 8, 16]; const startNumber = 1; // Using the above function, write a function that returns a promise resulting with the aggregate of multiplying startNumber with the provided multipliers. Note that the number should be getting bigger than the multipliers as you go through multipliers. // Solution function aggregate(num, multiples) { return Promise.reduce(multiples, (mult, agg) => mult * agg, num); }
  • Book Listing Exercise - /dotdash/book-listing-exercise
    Last edited 7 years ago
    const express = require("@runkit/runkit/express-endpoint/1.0.0"); const request = require('request'); const Promise = require('bluebird'); const xml2js = require('xml2js'); const app = express(exports); const parseString = Promise.promisify(xml2js.parseString); const requestAsync = Promise.promisify(request); const DEFAULT_PAGE = 1; function mapBook(bookData) { const data = bookData.best_book.shift(); const authorName = data.author.pop().name.shift(); const imageUrl = data.image_url.shift(); const title = data.title.shift(); return { authorName, imageUrl, title }; } function transformResponse(response) { const data = response.GoodreadsResponse.search.shift(); const items = data.results.shift().work; const list = items.map(mapBook); const total = parseInt(data['total-results'].shift(), 10); return { list, total }; } app.all('*', (req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', 'origin, x-requested-with, content-type, credentials, accept, Access-Control-Allow-Origin'); res.header('Access-Control-Allow-Methods', 'GET, OPTIONS'); next(); }); app.get('/search/:term', async function(req, res) { const page = req.query.page || DEFAULT_PAGE; const requestOptions = { baseUrl : 'https://www.goodreads.com/', qs : { key : 'fylVXMzp2hU0m4YFUMSAUg', page, q : req.params.term }, uri : '/search/index.xml' }; try { const searchResponse = await requestAsync(requestOptions); const results = await parseString(searchResponse.body); res.send(transformResponse(results)); } catch(e) { res .status(500) .send(e); } });