Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions JavaScript/Tasks/1-thenable.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,21 @@

// Task: change `iterate` contract from callbacks to Thenable

const iterate = (items, callback) => {
for (const item of items) {
callback(item);
}
};
const iterate = (items) => ({
then(resolve) {
for (const item of items) {
resolve(item);
}
},
});

const electronics = [
{ name: 'Laptop', price: 1500 },
{ name: 'Keyboard', price: 100 },
{ name: 'HDMI cable', price: 10 },
];

// Use await syntax to get items
iterate(electronics, (item) => {
console.log(item);
});
iterate(electronics).then(item=>console.log(item))



4 changes: 3 additions & 1 deletion JavaScript/Tasks/2-reject.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
const iterate = (items) => {
let index = 0;
return {
then(fulfill /*reject*/) {
then(fulfill, reject) {
// Call both: fulfill and reject
if (index < items.length) {
fulfill(items[index++]);
} else {
reject(new Error('No items'))
}
},
};
Expand Down
25 changes: 15 additions & 10 deletions JavaScript/Tasks/3-class.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
// Task: rewrite to `class Iterator` implementing
// Thenable contract with private fields.

const iterate = (items) => {
let index = 0;
return {
then(fulfill /*reject*/) {
if (index < items.length) {
fulfill(items[index++]);
class Iterator {
#items;
constructor(items){
this.#items = items;
}

then(fulfill /*reject*/) {
const item = this.#items.shift()
if (item) {
fulfill(item);
}
},
};
};
}
}



const electronics = [
{ name: 'Laptop', price: 1500 },
Expand All @@ -21,7 +26,7 @@ const electronics = [
];

(async () => {
const items = iterate(electronics);
const items = new Iterator(electronics);
// Use `new Iterator(electronics)`
const item1 = await items;
console.log(item1);
Expand Down