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);
}