Skip to content

Commit 12bbb22

Browse files
Create promisesLastName.js
1 parent 5211598 commit 12bbb22

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

Javascript/promisesLastName.js

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*Promises in Javascript
2+
A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.
3+
4+
5+
6+
Problem Description
7+
Given as inputs to the getLastNames() function
8+
9+
A string representing a first name, firstName.
10+
An Array of person objects with properties, "firstName" and “lastName”
11+
12+
13+
Return a JavaScript Promise which is either
14+
rejected with a message "Invalid" if none of the person objects “firstName” property matches the input first name, firstName
15+
resolved with an sorted Array of "lastName" property values of objects whose “firstName” property matches the given first name, firstName
16+
17+
Note
18+
19+
The "lastName"s array should be sorted in alphabetical order
20+
21+
Function to return a Promise object and not a String or Array
22+
*/
23+
24+
function getLastNames(firstName, people) {
25+
26+
return new Promise(function (resolve, reject) {
27+
let matchingPeeps = [];
28+
matchingPeeps = people.filter((obj) => {
29+
return obj.firstName === firstName
30+
})
31+
32+
if (matchingPeeps.length === 0) {
33+
reject("Invalid");
34+
} else {
35+
let unsortedArray = [];
36+
37+
for (let i = 0; i < matchingPeeps.length; i++) {
38+
let lastName = matchingPeeps[i].lastName;
39+
unsortedArray.push(lastName);
40+
}
41+
unsortedArray.sort();
42+
resolve(unsortedArray);
43+
}
44+
})
45+
}
46+
47+
48+
let firstName = 'David'
49+
50+
people = [
51+
52+
{
53+
54+
firstName: 'David',
55+
56+
lastName: 'Dobrick'
57+
58+
},
59+
60+
{
61+
62+
firstName: 'David',
63+
64+
lastName: 'Beckham'
65+
66+
},
67+
68+
{
69+
70+
firstName: 'Chris',
71+
72+
lastName: 'Lee'
73+
74+
},
75+
76+
{
77+
78+
firstName: 'James',
79+
80+
lastName: 'Bond'
81+
82+
},
83+
84+
]
85+
86+
console.log(getLastNames(firstName, people))
87+
module.exports = getLastNames;

0 commit comments

Comments
 (0)