-
Notifications
You must be signed in to change notification settings - Fork 0
/
homework1.js
92 lines (72 loc) · 2.36 KB
/
homework1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function makeRequest (url, callback){
let req= new XMLHttpRequest();
req.onreadystatechange = function(){
if (req.status == 200){
callback (req.responseText);
}
};
req.open("GET", url, false);
req.send(null);
}
// you need to write code here, because only in callback you will receive data not earlier
function dealWithData(data) {
let obj= JSON.parse(data);
let arr=[];
for (let i=0; i<obj.length; i++){
let temp= new DataClass(obj[i].userId, obj[i].id, obj[i].title, obj[i].body);
arr.push(temp);
}
sortByBiggestBody(arr);
console.log(arr);
}
function sortByBiggestBody(data){
for (var i=0; i<=data.length; i++){
for (var j=0; j<data.length-1; j++){
if (data[j].body&&data[j+1].body){
if (data[j].body.length< data[j+1].body.length){
let temp= data[j];
data[j]= data[j+1];
data[j+1]= temp;
}
}
}
}
}
class DataClass {
constructor (userId, id, title, body){
this.userId= userId;
this.id= id;
this.title=title;
this.body= body;
}
/*function biggestBody(data){
let largestBodyLength=0;
let largestBody;
for (var i=0; i<=data.length; i++){
if (this.body.length> largestBodyLength){
largestBodyLength= this.body[i].length;
largestBody= this.body[i];
}
}
return largestBody;
}
function sortByBiggestBody(data){
for (var i=0; i<=data.length; i++){
for (var j=0; j<=data.length-1; j++){
if (this.body[i+1]> this.body[i]){
let temp= this.body[i];
this.body[i]= this.body[i+1];
this.body[i+1]= temp;
}
}
}
return data;
}*/
}
let ourUrl = "https://jsonplaceholder.typicode.com/posts";
let dataInfo= makeRequest (ourUrl, dealWithData);
//console.log(dataInfo);
let class1= new DataClass (dataInfo);
//console.log(DataClass.biggestBody(class1)); // you should call class1.biggestBody(dataInfo) instead DataClass.biggestBody
// DataClass is a type of variables, like string or integer