Java 解决Movie Titles中缺失代码的片段,完成一个挑战更多

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48448432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:51:42  来源:igfitidea点击:

Fragment of missing code in the solution Movie Titles, complete a challenge more

javajsonhttp

提问by jasa1704

To solve this challenge, write an HTTP GET method to retrieve information from a particular movie database. Complete the function in the editor; it has one parameter: a string, substr. The function must perform the following tasks:

为了解决这个挑战,编写一个 HTTP GET 方法来从特定的电影数据库中检索信息。完成编辑器中的功能;它有一个参数:一个字符串,substr。该函数必须执行以下任务:

  1. Query https://jsonmock.hackerrank.com/api/movies/search/?Title=substr(where substr is the value of substr). The query response from the website is a JSON response with the following five fields:
  1. 查询https://jsonmock.hackerrank.com/api/movies/search/?Title=substr(其中 substr 是 substr 的值)。来自网站的查询响应是具有以下五个字段的 JSON 响应:

? page: The current page.

? 页:当前页面。

? per_page: The maximum number of results per page.

? per_page:每页的最大结果数。

? total: The total number of such movies having the substring substr in their title.

? 总计:标题中包含子字符串 substr 的此类电影的总数。

? total_pages: The total number of pages which must be queried to get all the results.

? total_pages:必须查询以获取所有结果的总页数。

? data: An array of JSON objects containing movie information where the Title field denotes the title of the movie. Note that this field is paginated so, in order to incorporate pagination, you must query https://jsonmock.hackerrank.com/api/movies/search/?Title=substr&page=pageNumber, where pageNumber is an integer denoting the page you would like to view (e.g., 1, 2, etc.).

? data:包含电影信息的 JSON 对象数组,其中 Title 字段表示电影的标题。请注意,此字段已分页,因此为了合并分页,您必须查询https://jsonmock.hackerrank.com/api/movies/search/?Title=substr&page=pageNumber,其中 pageNumber 是一个整数,表示您要访问的页面喜欢查看(例如,1、2 等)。

  1. Create an array of strings named titles to store total elements. For each page of results, store the Title of each movie in the titles array.

  2. Sort titles in ascending order and return it as your answer.

  1. 创建一个名为 titles 的字符串数组来存储总元素。对于每页结果,将每部电影的标题存储在 titles 数组中。

  2. 按升序对标题进行排序并将其作为您的答案返回。

Input Format

输入格式

A single string, substr, denoting the substring you must query for.

单个字符串 substr,表示您必须查询的子字符串。

Output Format

输出格式

Return an array of strings corresponding to movie titles with susbtr in their Title, sorted in ascending order.

返回与标题中带有 susbtr 的电影标题相对应的字符串数组,按升序排序。

Sample Input 0

样本输入 0

spiderman

蜘蛛侠

Sample Output 0

样本输出 0

  • Amazing Spiderman Syndrome
  • Fighting, Flying and Driving: The Stunts of Spiderman 3
  • Hollywood's Master Storytellers: Spiderman Live
  • Italian Spiderman
  • Spiderman
  • Spiderman
  • Spiderman 5
  • Spiderman and Grandma
  • Spiderman in Cannes
  • Superman, Spiderman or Batman
  • The Amazing Spiderman T4 Premiere Special
  • The Death of Spiderman
  • They Call Me Spiderman
  • 惊人的蜘蛛侠综合症
  • 战斗、飞行和驾驶:蜘蛛侠 3 的特技
  • 好莱坞的讲故事大师:蜘蛛侠现场直播
  • 意大利蜘蛛侠
  • 蜘蛛侠
  • 蜘蛛侠
  • 蜘蛛侠 5
  • 蜘蛛侠和奶奶
  • 戛纳的蜘蛛侠
  • 超人、蜘蛛侠或蝙蝠侠
  • 超凡蜘蛛侠 T4 首映特辑
  • 蜘蛛侠之死
  • 他们叫我蜘蛛侠

Explanation 0

说明 0

For this example, we want all the movie titles containing the substring spiderman. The response for the query https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=1is:

对于这个例子,我们想要包含子字符串蜘蛛侠的所有电影标题。查询https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=1的响应是:

{ 
  "page": "1",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [
{
  "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BYjFhN2RjZTctMzA2Ni00NzE2LWJmYjMtNDAyYTllOTkyMmY3XkEyXkFqcGdeQXVyNTA0OTU0OTQ@._V1_SX300.jpg",
  "Title": "Italian Spiderman",
  "Type": "movie",
  "Year": "2007",
  "imdbID": "tt2705436"
},
{
  "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjQ4MzcxNDU3N15BMl5BanBnXkFtZTgwOTE1MzMxNzE@._V1_SX300.jpg",
  "Title": "Superman, Spiderman or Batman",
  "Type": "movie",
  "Year": "2011",
  "imdbID": "tt2084949"
},
{
  "Poster": "N/A",
  "Title": "Spiderman",
  "Type": "movie",
  "Year": "1990",
  "imdbID": "tt0100669"
},
{
  "Poster": "N/A",
  "Title": "Spiderman",
  "Type": "movie",
  "Year": "2010",
  "imdbID": "tt1785572"
},
{
  "Poster": "N/A",
  "Title": "Fighting, Flying and Driving: The Stunts of Spiderman 3",
  "Type": "movie",
  "Year": "2007",
  "imdbID": "tt1132238"
},
{
  "Poster": "http://ia.media-imdb.com/images/M/MV5BMjE3Mzg0MjAxMl5BMl5BanBnXkFtZTcwNjIyODg5Mg@@._V1_SX300.jpg",
  "Title": "Spiderman and Grandma",
  "Type": "movie",
  "Year": "2009",
  "imdbID": "tt1433184"
},
{
  "Poster": "N/A",
  "Title": "The Amazing Spiderman T4 Premiere Special",
  "Type": "movie",
  "Year": "2012",
  "imdbID": "tt2233044"
},
{
  "Poster": "N/A",
  "Title": "Amazing Spiderman Syndrome",
  "Type": "movie",
  "Year": "2012",
  "imdbID": "tt2586634"
},
{
  "Poster": "N/A",
  "Title": "Hollywood's Master Storytellers: Spiderman Live",
  "Type": "movie",
  "Year": "2006",
  "imdbID": "tt2158533"
},
{
  "Poster": "N/A",
  "Title": "Spiderman 5",
  "Type": "movie",
  "Year": "2008",
  "imdbID": "tt3696826"
}]}

The response for the query https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=2is:

查询https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=2的响应是:

{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [
{
  "Poster": "N/A",
  "Title": "They Call Me Spiderman",
  "Type": "movie",
  "Year": "2016",
  "imdbID": "tt5861236"
},
{
  "Poster": "N/A",
  "Title": "The Death of Spiderman",
  "Type": "movie",
  "Year": "2015",
  "imdbID": "tt5921428"
},
{
  "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
  "Title": "Spiderman in Cannes",
  "Type": "movie",
  "Year": "2016",
  "imdbID": "tt5978586"
}]}

The respective values of the Title field for each movie in each response page are:

每个响应页面中每部电影的标题字段的相应值是:

  • Italian Spiderman
  • Superman, Spiderman or Batman
  • Spiderman
  • Spiderman
  • Fighting, Flying and Driving: The Stunts of Spiderman 3
  • Spiderman and Grandma
  • The Amazing Spiderman T4 Premiere Special
  • Amazing Spiderman Syndrome
  • Hollywood's Master Storytellers: Spiderman Live
  • Spiderman 5
  • They Call Me Spiderman
  • The Death of Spiderman
  • Spiderman in Cannes
  • 意大利蜘蛛侠
  • 超人、蜘蛛侠或蝙蝠侠
  • 蜘蛛侠
  • 蜘蛛侠
  • 战斗、飞行和驾驶:蜘蛛侠 3 的特技
  • 蜘蛛侠和奶奶
  • 超凡蜘蛛侠 T4 首映特辑
  • 惊人的蜘蛛侠综合症
  • 好莱坞的讲故事大师:蜘蛛侠现场直播
  • 蜘蛛侠 5
  • 他们叫我蜘蛛侠
  • 蜘蛛侠之死
  • 戛纳的蜘蛛侠

We then store each title in our titles array, sort it in ascending order, and return it as our answer.

然后我们将每个标题存储在我们的 titles 数组中,按升序对其进行排序,并将其作为我们的答案返回。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.net.*;
import com.google.gson.*;

public class Solution {
/*
 * Complete the function below.
 */

static String[] getMovieTitles(String substr) {

      //complete function here
}


public static void main(String[] args) throws IOException{
    Scanner in = new Scanner(System.in);
    final String fileName = System.getenv("OUTPUT_PATH");
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    String[] res;
    String _substr;
    try {
        _substr = in.nextLine();
    } catch (Exception e) {
        _substr = null;
    }

    res = getMovieTitles(_substr);
    for(int res_i=0; res_i < res.length; res_i++) {
        bw.write(String.valueOf(res[res_i]));
        bw.newLine();
    }

    bw.close();
    } 
}

采纳答案by a2441918

This is a Javascript answer.

这是一个 Javascript 答案。

var https = require('https');

function fetchData(substr) {
    pageNum = 1;
    let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNum;
    https.get(url, (res) => {
        res.setEncoding('utf8');
        res.on('data', function(body) {
            let dataRec = JSON.parse(body);
            let movies = dataRec.data;
            let totPages = dataRec.total_pages;
            let sortArray = [];
            movies.map((a) => {
              sortArray.push(a.Title)
            })
            for (let i = 2; i <= totPages; i++) {
                let newPage = i;
                let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;
                https.get(url1, (res) => {
                    res.setEncoding('utf8');
                    res.on('data', function(body) {
                        let newData = JSON.parse(body);
                        let newMovies = newData.data;
                        for (let i = 0; i < newMovies.length; i++) {
                            sortArray.push(newMovies[i].Title);
                        }
                        console.log(sortArray.sort());
                    })
                })
            }
        })
    })
}

//primary function 
function getMovieTitles(substr) {
    fetchData(substr);
}

getMovieTitles("spiderman");

回答by Rajeev

import com.fasterxml.Hymanson.annotation.JsonIgnoreProperties;
import com.fasterxml.Hymanson.annotation.JsonInclude;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import com.fasterxml.Hymanson.annotation.JsonInclude.Include;

/**
 * 
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class MovieTitle {

    @JsonProperty("Poster")
    private String poster;

    @JsonProperty("Title")
    private String title;

    @JsonProperty("Type")
    private String type;

    @JsonProperty("Year")
    private String year;

    @JsonProperty("imdbID")
    private String imdbID;

    public String getPoster() {
        return poster;
    }

    public void setPoster(String poster) {
        this.poster = poster;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getImdbID() {
        return imdbID;
    }

    public void setImdbID(String imdbID) {
        this.imdbID = imdbID;
    }

}


import java.util.List;

import com.fasterxml.Hymanson.annotation.JsonIgnoreProperties;
import com.fasterxml.Hymanson.annotation.JsonInclude;
import com.fasterxml.Hymanson.annotation.JsonProperty;
import com.fasterxml.Hymanson.annotation.JsonInclude.Include;

/**
 * @author
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class SearchResult {

    @JsonProperty("page")
    private String page;

    @JsonProperty("per_page")
    private String per_page;

    @JsonProperty("total")
    private String total;

    @JsonProperty("total_pages")
    private String total_pages;

    @JsonProperty("data")
    private List<MovieTitle> movieTitles;

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public String getPer_page() {
        return per_page;
    }

    public void setPer_page(String per_page) {
        this.per_page = per_page;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getTotal_pages() {
        return total_pages;
    }

    public void setTotal_pages(String total_pages) {
        this.total_pages = total_pages;
    }

    public List<MovieTitle> getMovieTitles() {
        return movieTitles;
    }

    public void setMovieTitles(List<MovieTitle> movieTitles) {
        this.movieTitles = movieTitles;
    }

}

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.rest.model.SearchResult;

/**
 * @author
 *
 */
public class SprngRestClient {

    public static void main(String args[]) {
        getMovieTitles("spiderman");
    }

    static void getMovieTitles(String movietitle) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("sample.proxy", 8080));
        requestFactory.setProxy(proxy);
        List<String> moviewTitles = new ArrayList<String>();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        int pageNo = 0;
        int totalPages = 100000;
        while (pageNo != totalPages) {
            pageNo = pageNo + 1;
            SearchResult quote = restTemplate.getForObject(
                    "https://jsonmock.hackerrank.com/api/movies/search/?Title=" + movietitle + "&page=" + pageNo,
                    SearchResult.class);
            moviewTitles.addAll(quote.getMovieTitles()
                                     .stream()
                                     .map(title -> title.getTitle())
                                     .collect(Collectors.toList()));
            pageNo = Integer.parseInt(quote.getPage());
            totalPages = Integer.parseInt(quote.getTotal_pages());
        }
        moviewTitles.sort((name1, name2) -> name1.compareTo(name2));
        moviewTitles.forEach(System.out::println);
    }

}

回答by AiU

here is the same code of a2441918 but improved! with promises less callbacks

这是与 a2441918 相同的代码,但有所改进!承诺减少回调

this code is testable and modular also ES6 style

这段代码是可测试和模块化的,也是 ES6 风格的

import the module

导入模块

const https = require('https');

the url should be dynamic ( this could be improved )

网址应该是动态的(这可以改进)

const url = (title, pageNum = 1) => 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + title + "&page=" + pageNum 

separate the get request this will allow to write it once and used as many times we need

将 get 请求分开,这将允许编写一次并根据需要多次使用

function requestGET(url) {
    return new Promise((resolve, reject) => {
        https.get(url, res => {
            console.log(res.statusCode, res.statusCode >= 400)
            if ( res.statusCode >= 200 && res.statusCode < 400 ) {
                res.on('data', body => {
                    resolve(body)
                })
            } 

            if(res.statusCode >= 400) {
                    // since it needs to parse the response
                    // in case of 400 sed back an empty object 
                    // on this method alone can add huge improvement
                    // but that will be a huge waste of time, 
                    // since great libraries are out there 
                    reject(JSON.stringify({}))
                }
            }).on('error', (e) => {
                console.error(`Got error: ${e.message}`);
        })
    })
}

this method will make code more readable

这种方法将使代码更具可读性

const convertToString = arr => {
    console.log(arr.join('\n'))
}

and finally the end calls:

最后最后调用:

function getMovieTitles(substr) {
    fetchData(substr);
}



const res = getMovieTitles('yfvuguoguogguoyguogouyg')

回答by Ravi Mishra

This is what you are looking for:

这就是你要找的:

String[] getMovieTitles(String substr) {
String response;
int startPage = 1;
int totalPages = Integer.MAX_VALUE;
List<String> titles = new ArrayList<>();
while (startPage <= totalPages) {
  try {
    URL obj = new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page=" + startPage);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    while ((response = in.readLine()) != null) {
      JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
      totalPages = convertedObject.get("total_pages").getAsInt();
      JsonArray data = convertedObject.getAsJsonArray("data");
      for (int i = 0; i < data.size(); i++) {
        String title = data.get(i).getAsJsonObject().get("Title").getAsString();
        titles.add(title);
      }
    }
    in.close();
    startPage++;
  } catch (Exception ex) {
    ex.printStackTrace();
  }

}
Collections.sort(titles);
return titles.toArray(new String[0]);
}

回答by Venkataramana

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import java.net.*;
import com.google.gson.*;

public class Solution{

static String[] getMovieTitles(String substr) {
    String response;
    int startPage = 1;
    int totalPages = Integer.MAX_VALUE;
    List<String> titles = new ArrayList<>();
    while (startPage <= totalPages) {
        try {
            URL obj = new URL(
                    "https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page=" + startPage);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            while ((response = in.readLine()) != null) {
                JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
                totalPages = convertedObject.get("total_pages").getAsInt();
                JsonArray data = convertedObject.getAsJsonArray("data");
                for (int i = 0; i < data.size(); i++) {
                    String title = data.get(i).getAsJsonObject().get("Title").getAsString();
                    titles.add(title);
                }
            }
            in.close();
            startPage++;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }
    Collections.sort(titles);
    return titles.toArray(new String[0]);
}

public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    final String fileName = System.getenv("OUTPUT_PATH");
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    String[] res;
    String _substr;
    try {
        _substr = in.nextLine();
    } catch (Exception e) {
        _substr = null;
    }

    res = getMovieTitles(_substr);
    for (int res_i = 0; res_i < res.length; res_i++) {
        bw.write(String.valueOf(res[res_i]));
        bw.newLine();
    }

    bw.close();
}

}

}

回答by Nisanth Sojan

Here is another version of a2441918with promises!!!.

这是带有承诺的a2441918 的另一个版本!!!。

"use strict";
const https = require("https");

const getMovieTitlesData = (title, page = 1) => {
  const url = `https://jsonmock.hackerrank.com/api/movies/search/?Title=${encodeURI(
    title
  )}&page=${page}`;

  const titles = [];
  return new Promise((resolve, reject) => {
    https
      .get(url, function(res) {
        let body = "";
        res.setEncoding("utf-8");
        res.on("data", function(chunk) {
          body += chunk;
        });
        res.on("end", function() {
          let json = JSON.parse(body);
          for (let i = 0; i < json.data.length; i++) {
            titles.push(json.data[i].Title);
          }
          // console.log(json);
          resolve({
            titles: titles,
            page: page,
            total_pages: json.total_pages
          });
        });
      })
      .on("error", function(e) {
        console.error("Got an error: ", e);
        reject(e);
      });
  });
};

function getMovieTitles(substr) {
  const promises = [];
  const titles = [];
  getMovieTitlesData(substr).then(result => {
    titles.push(...result.titles);
    for (let i = result.page + 1; i <= result.total_pages; i++) {
      promises.push(getMovieTitlesData(substr, i));
    }
    Promise.all(promises).then(datas => {
      datas.forEach(data => {
        titles.push(...data.titles);
      });
      console.log(titles.sort());
    });
  });
}

getMovieTitles("spiderman");

回答by Dulaj Kulathunga

You can use java 8 Stream APi

您可以使用 java 8 Stream API

    private String[] getMovieTitlesFromApi(String query) {
  List<String> titlesLst = new ArrayList<>();

IntStream.iterate(1, n -> n + 1).takeWhile(n -> n < totalPages).limit(totalPages).forEach(c -> {

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + URLEncoder.encode(query, "UTF-8") + "&page=" + c)
                    .openConnection().getInputStream()))) {

        Supplier<Stream<String>> contentStream =  reader::lines;

        Optional<JsonObject> objectAsJob = contentStream.get()
                .map(contentStreamLine -> new Gson().fromJson(contentStreamLine, JsonObject.class)).findFirst();
        totalPages = objectAsJob.map(convertedLines -> convertedLines.get("total_pages").getAsInt()).get();
        Optional<JsonArray> dataFilter = objectAsJob.map(convertedLines -> convertedLines.getAsJsonArray("data"));

        IntStream.iterate(0, n -> n + 1).takeWhile(n -> n < dataFilter.get().size()).forEach(dataLines -> {
            titlesLst.add(dataFilter.get().get(dataLines).getAsJsonObject().get("Title").getAsString());
            Collections.sort(titlesLst);
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

    totalPages++;
});

storeMovieTitlesInCache(query,  titlesLst.stream().distinct().collect(Collectors.toList()).toArray(new String[0]));
return titlesLst.toArray(new String[0]);
}

回答by Iqra.

Here is my solution in python for this:

这是我在 python 中的解决方案:

import requests
import json

def getMovieTitles(substr):
    titles = []  
    data = requests.get("https://jsonmock.hackerrank.com/api/movies/search/?Title={}".format(substr))  
    response = json.loads(data.content.decode('utf-8'))    
    for page in range(0, response["total_pages"]):       
        page_response = requests.get("https://jsonmock.hackerrank.com/api/movies/search/?Title={}&amp;page={}".format(substr, page + 1))    
        page_content = json.loads(page_response.content.decode('utf-8'))
        #print ('page_content', page_content, 'type(page_content)', type(page_content))    
        for item in range(0, len(page_content["data"])):           
             titles.append(str(page_content["data"][item]["Title"]))  
    titles.sort()  
    return titles

print(getMovieTitles("spiderman"))

回答by Yesid

Using async await

使用异步等待

const https = require('https');

// function returns a Promise
const getPromise = (movie_title, page = 1) => {
  return new Promise((resolve, reject) => {
    https.get(
      `https://jsonmock.hackerrank.com/api/movies/search/?Title=${movie_title}&page=${page}`,
      response => {
        let chunks_of_data = [];

        response.on('data', fragments => {
          chunks_of_data.push(fragments);
        });
        response.on('end', () => {
          let data = Buffer.concat(chunks_of_data);
          resolve(JSON.parse(data));
        });
        response.on('error', error => {
          reject(error);
        });
      }
    );
  });
};

// async function to make http request
const makeSynchronousRequest = async movie_title => {
  try {
    // maing a req for number of pages
    let http_promise = getPromise(movie_title);
    let response_body = await http_promise;
    let titles = [];
    for (let page_num = 1; page_num <= response_body.total_pages; page_num++) {
      // maing a req for titles of movies
      let http_promise = getPromise(movie_title, page_num);
      let response_body = await http_promise;
      // holds response from server that is passed when Promise is resolved
      response_body.data.forEach(item => {
        titles.push(item.Title);
      });
    }
    console.log(titles.sort());
  } catch (error) {
    // Promise rejected
    console.log(error);
  }
};

function getMovieTitles(movie_title) {
  makeSynchronousRequest(movie_title);
}

getMovieTitles('batman');

回答by ssp4all

If anyone looking for the GET AUTHOR ARTICLESproblem then below is my Python solution

如果有人在寻找GET AUTHOR ARTICLES问题,那么下面是我的 Python 解决方案

import requests
import json

def getArticleTitles(author):
    # Write your code here
    if not author:  return []
    titles = []
    st, total = 1, float('inf')
    while st <= total:
        url = "https://jsonmock.hackerrank.com/api/articles?author={0}&page={1}".format(author, st)
        response = requests.get(url)
        res = json.loads(response.content)
        total = res['total_pages']

        for t in res['data']:
            if not t['title'] and not t['story_title']:
                continue
            elif not t['title']:
                titles += [t['story_title']]
            else:
                titles += [t['title']]
        st += 1
    return titles