React and Redux Sagas Weather Report App Tutorial

Overview

In this tutorial we’re going to build a weather Report by using React Boilerplate . Few months ago I did a code testing by using angualr1.5 and now I like to do it again by using current popular tools react, redux and sagas.  React Boilerplate is not for beginner level, and I won’t explain any concept of react, redux, and sagas. There already has too many tutorial about it.

React Boilerplate is very mature start setup for  building scalable react app and suit for any complex real life project.

After finish that should look like this:

Screen Shot 2018-01-19 at 4.06.00 pm

Now let start it:

Part 1 – Setting up the base project and template.

  1. Create a folder, named “weather-react-redux-saga-app”
  2. cd weather-react-redux-saga-app
  3. run git clone https://github.com/react-boilerplate/react-boilerplate.git .
  4. npm run setup ( install the package and start the project.)
  5. npm run clean ( get rid of the template that react boilerplate provides)
  6. npm start ( now project setup done)

Part 2 – Create the container and components by  using React Boilerplate  provide component generate command. I will create one container component and two stateless component (WeaterListContainer and WeatherList stateless component and Weather component).

  1. run command ‘npm run generate container

move the arrow select React.component

what should it be called?

Do you want headers?

Do you want an actions/constants/selectors/reducer tuple for this container? y

Do you want sagas for asynchronous flows?y

Do you want i18n messages (i.e. will this component use text)?n

Do you want to load resources asynchronously?n

  2 . run command ‘npm run generate component

move the arrow select Stateless Function then enter

       What should it be called? WeatherList

Do you want i18n messages (i.e. will this component use text)?n

 Do you want to load the component asynchronously? n

  follow step 2 create Weather component.

  3. go to HomePage/index edit it using the WeatherListContainer

Screen Shot 2018-01-22 at 2.02.31 pm

Next post will explain how to working with api: openweathermap to get data by using saga and display it to the page.

to be continue….

 

Advertisements

Day of the Programmer

Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700.

From 1700 to 2700, Russia’s official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31th was February 14 th . This means that in 1918, February 14th was the 32th day of the year in Russia.

In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 ; in the Gregorian calendar, leap years are either of the following:

Divisible by 400.
Divisible by 4 and not divisible by 100.
Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

Input Format

A single integer denoting year y.

Constraints

Output Format

Print the full date of Day of the Programmer during year y in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function solve(year){
    if (year == 1918)
        return '26.09.1918'
    else if (((year  1918) && (year%400 == 0 || ((year%4 == 0) && (year%100 != 0)))))
        return '12.09.' + year
    else
        return '13.09.' + year
}

function main() {
    var year = parseInt(readLine());
    var result = solve(year);
    process.stdout.write(""+result+"\n");

}

Breaking the Records

Maria plays n games of college basketball in a season. Because she wants to go pro, she tracks her points scored per game sequentially in an array defined as score = [S0,S1,…,Sn-1] . After each game i , she checks to see if score Si breaks her record for most or least points scored so far during that season.

Given Maria’s array of scores for a season of n games, find and print the number of times she breaks her record for most and least points scored during the season.

Note: Assume her records for most and least points at the start of the season are the number of points scored during the first game of the season.

Input Format

The first line contains an integer denoting (the number of games).
The second line contains space-separated integers describing the respective values of .

 

 

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function getRecord(s){
    // Complete this function
    var result = [];
    var countMax=0, countMin=0 ,max = s[0], min = s[0];
    for(var i=1; i max){ max = s[i];  countMax++; }
        if(s[i] < min){ min = s[i];  countMin++; }
    }
    result.push(countMax); 
    result.push(countMin);
    return result;
    
}

function main() {
    var n = parseInt(readLine());
    s = readLine().split(' ');
    s = s.map(Number);
    var result = getRecord(s);
    console.log(result.join(" "));

}

Between Two Sets

Consider two sets of positive integers,  and . We say that a positive integer, , is between sets  and  if the following conditions are satisfied:

  1. All elements in  are factors of .
  2.  is a factor of all elements in .

In other words, some  is between  and  if that value of  satisfies  for every  in  and also satisfies  for every  in . For example, if  and , then our possible  values are and .

Given  and , find and print the number of integers (i.e., possible ‘s) that are between the two sets.

Input Format

The first line contains two space-separated integers describing the respective values of  (the number of elements in set ) and  (the number of elements in set ).
The second line contains  distinct space-separated integers describing .
The third line contains  distinct space-separated integers describing .

Constraints

Output Format

Print the number of integers that are considered to be between  and .

Sample Input

2 3
2 4
16 32 96

Sample Output

3

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function getTotalX(a, b) {
    var maxA = 0, minB = 101, count=0, n=a.length, m=b.length;

    for(var a_i=0; a_i  maxA ? tmpa : maxA;
    }

    for(var b_i=0; b_i < m; b_i++){
        var tmpb = b[b_i];
        minB = tmpb < minB ? tmpb : minB;
    }


  for(var i = maxA; i <= minB; i += maxA)
  {
      var factorA = true, factorB = true;
      //Check if all A are a factor of i
      for(var ii = 0; ii < n; ii++){
          if(i%a[ii] !=0){
              factorA = false;
              continue;
           }
      }

      //Check if i is a factor of all B
      for(var jj = 0; jj < m; jj++){
           if(b[jj]%i != 0){
              factorB = false;
              continue;
            }
      }
      
      if(factorA && factorB)
        count++;
  }
    
  return count;
    
}

function main() {
    var n_temp = readLine().split(' ');
    var n = parseInt(n_temp[0]);
    var m = parseInt(n_temp[1]);
    a = readLine().split(' ');
    a = a.map(Number);
    b = readLine().split(' ');
    b = b.map(Number);
    var total = getTotalX(a, b);
    process.stdout.write("" + total + "\n");

}

 

Apple and Orange

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where  is the start point and  is the end point. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point  and the orange tree is at point .

Apple and orange(2).png

When a fruit falls from its tree, it lands  units of distance from its tree of origin along the -axis. A negative value of  means the fruit fell  units to the tree’s left, and a positive value of  means it falls  units to the tree’s right.

Given the value of  for  apples and  oranges, can you determine how many apples and oranges will fall on Sam’s house (i.e., in the inclusive range )? Print the number of apples that fall on Sam’s house as your first line of output, then print the number of oranges that fall on Sam’s house as your second line of output.

Input Format

The first line contains two space-separated integers denoting the respective values of  and .
The second line contains two space-separated integers denoting the respective values of  and .
The third line contains two space-separated integers denoting the respective values of  and .
The fourth line contains  space-separated integers denoting the respective distances that each apple falls from point .
The fifth line contains  space-separated integers denoting the respective distances that each orange falls from point .

Constraints

Output Format

Print two lines of output:

  1. On the first line, print the number of apples that fall on Sam’s house.
  2. On the second line, print the number of oranges that fall on Sam’s house.

Sample Input 0

7 11
5 15
3 2
-2 2 1
5 -6

Sample Output 0

1
1

Explanation 0

The first apple falls at position .
The second apple falls at position .
The third apple falls at position .
The first orange falls at position .
The second orange falls at position .
Only one fruit (the second apple) falls within the region between  and , so we print  as our first line of output.
Only the second orange falls within the region between  and , so we print  as our second line of output.

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var s_temp = readLine().split(' ');
    var s = parseInt(s_temp[0]);
    var t = parseInt(s_temp[1]);
    var a_temp = readLine().split(' ');
    var a = parseInt(a_temp[0]);
    var b = parseInt(a_temp[1]);
    var m_temp = readLine().split(' ');
    var m = parseInt(m_temp[0]);
    var n = parseInt(m_temp[1]);
    apple = readLine().split(' ');
    apple = apple.map(Number);
    orange = readLine().split(' ');
    orange = orange.map(Number);
    
    var countApple = 0;
    var countOrange = 0;
    apple.forEach(function(e) {
        if((a+e)>= s && (a+e)<=t) countApple++; }); orange.forEach(function(e) { if((b+e)>= s && (b+e)<=t)
           countOrange++;
    });
    
    process.stdout.write(countApple + "\n" + countOrange);
}

 

Grading Students

HackerLand University has the following grading policy:

  • Every student receives a  in the inclusive range from  to .
  • Any  less than  is a failing grade.

Sam is a professor at the university and likes to round each student’s  according to these rules:

  • If the difference between the  and the next multiple of  is less than , round  up to the next multiple of .
  • If the value of  is less than , no rounding occurs as the result will still be a failing grade.

For example,  will be rounded to  but  will not be rounded because the rounding would result in a number that is less than .

Given the initial value of  for each of Sam’s  students, write code to automate the rounding process. For each , round it according to the rules above and print the result on a new line.

Input Format

The first line contains a single integer denoting  (the number of students).
Each line  of the  subsequent lines contains a single integer, , denoting student ‘s grade.

Constraints

Output Format

For each  of the  grades, print the rounded grade on a new line.

Sample Input 0

4
73
67
38
33

Sample Output 0

75
67
40
33
Solution 

function solve(grades){
    var result = [];
    for(var i= 1; i<grades.length; i++){
       if(grades[i] < 38 || grades[i] % 5 <3)
          result.push(grades[i]);
       else
          result.push(grades[i] + (5- (grades[i] % 5)))
    }
    return result;
}

function main() {
    var n = parseInt(readLine());
    var grades = [];
    for(var grades_i = 0; grades_i < n; grades_i++){
       grades[grades_i] = parseInt(readLine());
    }
    var result = solve(grades);
    console.log(result.join("\n"));
}

Birthday Cake Candles

Colleen is turning  years old! Therefore, she has  candles of various heights on her cake, and candle  has height . Because the taller candles tower over the shorter ones, Colleen can only blow out the tallest candles.

Given the  for each individual candle, find and print the number of candles she can successfully blow out.

Input Format

The first line contains a single integer, , denoting the number of candles on the cake.
The second line contains  space-separated integers, where each integer  describes the height of candle .

Constraints

Output Format

Print the number of candles Colleen blows out on a new line.

Sample Input 0

4
3 2 1 3

Sample Output 0

2

Explanation 0

We have one candle of height , one candle of height , and two candles of height . Colleen only blows out the tallest candles, meaning the candles where . Because there are  such candles, we print  on a new line.

Solution Answer

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function birthdayCakeCandles(n, ar) {
   
   var max=ar[0];
   var num=1;
 for (var i=1;i<n; i++){
   if (ar[i]>max){ 
      max=ar[i];
     num=1;
   }
   else if (ar[i]==max) num++;
   }
  return num;
    
}

function main() {
    var n = parseInt(readLine());
    ar = readLine().split(' ');
    ar = ar.map(Number);
    var result = birthdayCakeCandles(n, ar);
    process.stdout.write("" + result + "\n");

}

 

Mini-Max Sum

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Input Format

A single line of five space-separated integers.

Constraints

Each integer is in the inclusive range .

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.)

Sample Input

1 2 3 4 5
Sample Output

10 14

Solution Answer


function main() {
arr = readLine().split(' ');
arr = arr.map(Number);
var sortedArr = arr.sort();
var sum = sortedArr.reduce(function(sum, value) {
return sum + value;
}, 0);
process.stdout.write((sum - sortedArr[4]) + ' ' + (sum - sortedArr[0]));

}

TDD Test AngularJs Service $Http

In my last post I have hardcode the data into the service to let my test pass, now in this post I will change that service to by inject the $http service into my module and let it return httpPromise.

Here is my new movieApi.js file


(function(){
   "use strict";
   
  var app =  angular.module('moviesApi',[]);

    app.factory('moviesApi',function($http, $q){
        var service = {};
        var baseUrl = 'http://www.omdbapi.com/?v=1&';

        function httpPromise (url) {
			var deferred = $q.defer();
			$http.get(url)
				.success(function(data) {
					deferred.resolve(data);
				})
				.error(function(error) {
					deferred.reject(error);
				});
			return deferred.promise;
		}

        service.search = function(query) {
			return httpPromise(baseUrl + 's=' + 
                               encodeURIComponent(query));
		} 
                    
   return service;
 });
})()

Then my unit test fail, that is because now my service return a promise and it has not resolve yet, but my test expect data, for how to solve this issue, angularjs has provide $httpBackend for Fake HTTP backend implementation for unit testing application that use the $http service.

Here is the new test code:

$httpBackend;
beforeEach(module('moviesApi'));
         //angular.mock is under the globe variable, so I have remove it 
         //the beforeEach is jasmine provide if you have multiple test need 
         //the same  set up, it will automatic set for each test, will reduce copy code
         //for name convenience  I also changed the service's name 
         //to match the module name
        //then in the dependence inject angularjs allow your put the underscore 
        //for your inject service,it will pick it up
	beforeEach(inject(function(_moviesApi_,_$httpBackend_) {
		moviesApi = _moviesApi_;
                $httpBackend = _$httpBackend_;
	}));
    
    it('should return search movies data',function(){
        var response;
        var expectedUrl = 'http://www.omdbapi.com/?v=1&s=star%20wars';
        $httpBackend.when('GET',expectedUrl)
                .respond(200,moviesData); 
        
        moviesApi.search('star wars')
                .then(function(data){
                        response = data;
                });

        //the fake $httpBackend has function flush will resolve the data for you to       //test

        $httpBackend.flush();

        expect(response).toEqual(moviesData);
    });

Tips: as frondend developer also could using this Fake data create a service response, so you do not need waiting for the backend service finished to do your job.

 

Now the test will pass.

Have fun!

Full stack developer