Skip to content

Instantly share code, notes, and snippets.

@ps0305
Forked from aegorenkov/iterators.js
Created November 5, 2019 20:21
Show Gist options
  • Save ps0305/206a51d5344323a71173f7744d314ece to your computer and use it in GitHub Desktop.
Save ps0305/206a51d5344323a71173f7744d314ece to your computer and use it in GitHub Desktop.
HardParts Promises and Iterators
// Type JavaScript here and click "Run Code" or press Ctrl + s
console.log('Hello, world!');
// CHALLENGE 1
function sumFunc(arr) {
// YOUR CODE HERE
let accumulator = 0;
for (let i = 0; i < arr.length; i++) {
accumulator += arr[i];
}
return accumulator;
}
// Uncomment the lines below to test your work
const array = [1, 2, 3, 4];
console.log('Challenge 1A', sumFunc(array)); // -> should log 10
function returnIterator(arr) {
// YOUR CODE HERE
let index = 0;
return function() {
const value = arr[index];
index++;
return value;
}
}
// Uncomment the lines below to test your work
const array2 = ['a', 'b', 'c', 'd'];
const myIterator = returnIterator(array2);
console.log('Challenge 1B', myIterator()); // -> should log 'a'
console.log(myIterator()); // -> should log 'b'
console.log(myIterator()); // -> should log 'c'
console.log(myIterator()); // -> should log 'd'
// CHALLENGE 2
function nextIterator(arr) {
// YOUR CODE HERE
let index = 0;
const iterator = {
next: function () {
const value = arr[index];
index++;
return value;
}
}
return iterator;
}
// Uncomment the lines below to test your work
const array3 = [1, 2, 3];
const iteratorWithNext = nextIterator(array3);
console.log('Challenge 2', iteratorWithNext.next()); // -> should log 1
console.log(iteratorWithNext.next()); // -> should log 2
console.log(iteratorWithNext.next()); // -> should log 3
// CHALLENGE 3
function sumArray(arr) {
// YOUR CODE HERE
// use your nextIterator function
let accumulator = 0;
let iterator = nextIterator(arr);
let next = iterator.next();
while(next) {
accumulator += next;
next = iterator.next();
}
return accumulator
}
// Uncomment the lines below to test your work
const array4 = [1, 2, 3, 4];
console.log('Challenge 3', sumArray(array4)); // -> should log 10
// CHALLENGE 4
function setIterator(set) {
// YOUR CODE HERE
let setIterator = set.values();
const iterator = {
next: function () {
var next = setIterator.next();
return next['value'];
}
}
return iterator;
}
// Uncomment the lines below to test your work
const mySet = new Set('hey');
const iterateSet = setIterator(mySet);
console.log('Challenge 4', iterateSet.next()); // -> should log 'h'
console.log(iterateSet.next()); // -> should log 'e'
console.log(iterateSet.next()); // -> should log 'y'
// CHALLENGE 5
function indexIterator(arr) {
// YOUR CODE HERE
let index = 0;
const iterator = {
next: function () {
const value = arr[index];
index++;
return [index - 1, value];
}
}
return iterator;
}
// Uncomment the lines below to test your work
const array5 = ['a', 'b', 'c', 'd'];
const iteratorWithIndex = indexIterator(array5);
console.log('Challenge 5', iteratorWithIndex.next()); // -> should log [0, 'a']
console.log(iteratorWithIndex.next()); // -> should log [1, 'b']
console.log(iteratorWithIndex.next()); // -> should log [2, 'c']
// CHALLENGE 6
function Words(string) {
this.str = string;
}
Words.prototype[Symbol.iterator] = function() {
// YOUR CODE HERE
let index = 0;
const splitStr = this.str.split(/\s/);
return {
next: function () {
if (index < splitStr.length) {
const value = splitStr[index];
index ++;
return {value: value, done: false};
} else {
return { done: true };
}
}
}
}
// Uncomment the lines below to test your work
const helloWorld = new Words('Hello World');
for (let word of helloWorld) { console.log('Challenge 6', word); } // -> should log 'Hello' and 'World'
// CHALLENGE 7
function valueAndPrevIndex(array){
let index = 0;
return {
sentence: function() {
index++;
let indexName = index;
if (index - 1 === 0) {
indexName = "first";
}
return "" + array[index - 1] + " was found after index " + indexName;
}
}
}
const returnedSentence = valueAndPrevIndex([4,5,6])
console.log(returnedSentence.sentence());
console.log(returnedSentence.sentence());
console.log(returnedSentence.sentence());
// Challenge 1
function sayHello() {
function printHello() {
console.log('Challenge 1, 5', 'Hello');
}
setTimeout(printHello, 1000);
}
// Uncomment the line below when ready
sayHello(); // should log "Hello" after 1000ms
// Challenge 2
let promise = new Promise(function (resolve, reject) {
// ADD CODE HERE
setTimeout(resolve, 1000);
});
// Should print out "Resolved!"
// ADD CODE HERE
function displayResolve() {
console.log('Challenge 2', 'Resolved!');
}
promise.then(displayResolve);
// Challenge 3
promise = new Promise(function(resolve, reject) {
// ADD CODE HERE
reject();
})
// Should print out "Reject!"
// ADD CODE HERE
function displayRejected() {
console.log('Challenge 3', 'Rejected!');
}
promise.catch(displayRejected);
// Challenge 4
promise = new Promise(function (resolve, reject) {
// ADD CODE HERE
resolve();
});
// Uncomment the lines below when ready
promise.then(function () {
console.log('Challenge 4', 'Promise has been resolved!')
});
console.log('Challenge 4', "I'm not the promise!");
// Challenge 5
function delay(){
return new Promise(function (resolve, reject) {
setTimeout(resolve, 1000);
});
}
// Uncomment the code below to test
// This code should log "Hello" after 1000ms
delay().then(sayHello);
// Challenge 6
//
// ADD CODE BELOW
const secondPromise = new Promise(function (resolve, reject) {
resolve('Second!');
});
const firstPromise = new Promise(function (resolve, reject) {
resolve(secondPromise);
})
firstPromise.then((value) => console.log('Challenge 6', value));
// Challenge 7
const fakePeople = [
{ name: 'Rudolph', hasPets: false, currentTemp: 98.6 },
{ name: 'Zebulon', hasPets: true, currentTemp: 22.6 },
{ name: 'Harold', hasPets: true, currentTemp: 98.3 },
]
const fakeAPICall = (i) => {
const returnTime = Math.floor(Math.random() * 1000);
return new Promise((resolve, reject) => {
if (i >= 0 && i < fakePeople.length) {
setTimeout(() => resolve(fakePeople[i]), returnTime);
} else {
reject({ message: "index out of range" });
}
});
};
function getAllData() {
// CODE GOES HERE
const apiPromises = [fakeAPICall(0), fakeAPICall(1), fakeAPICall(2)]
return Promise.all(apiPromises)
.then(function(values) {
return values;
});
}
getAllData().then((values) => console.log('Challenge 7', values));
Promises
Challenge 1
Let's start by reviewing asynchronous functions! Using setTimeout, print the string 'Hello!' after 1000ms.
Challenge 2
Create a promise. Have it resolve with a value of 'Resolved!' in resolve after a delay of 1000ms, using setTimeout. Print the contents of the promise after it has been resolved by passing console.log to .then
Challenge 3
Create another promise. Now have it reject with a value of "Rejected!" without using setTimeout. Print the contents of the promise after it has been rejected by passing console.log to .catch
Challenge 4
Promises are asynchronous and we're now going to prove that they indeed are! Create a promise and have it resolve with the value of "Promise has been resolved!" Then uncomment the code at bottom of Challenge 4. What order do we expect "Promise has been resolved!" and "I'm not the promise!" to print? Why?
Challenge 5
Write a function delay that returns a promise. And that promise should return a setTimeout that calls resolve after 1000ms
Challenge 6
This challenge we'll chain promises together using ".then" Create two variables: firstPromise and secondPromise Set secondPromise to be a promise that resolves to "Second!" Set firstPromise to be a promise that resolves to secondPromise Call the firstPromise with a ".then", which will return the secondPromise> promise. Then print the contents of the promise after it has been resolved by passing console.log to .then
Challenge 7
We have a API that gets data from a database, it takes an index parameter and returns a promise Your challenge is to use Promise.all to make 3 API calls and return all the data when the calls are complete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment