Sunday, 18 June 2017

javascript

1. data type

    string, number, boolean, null, undefined              //primitive, everything else object

    object = {type:"fiat", color:"white"};                   //object

    function Person(first, last, age, eyecolor) {         //constructor function, 1st class object
        this.firstName = first;
        this.lastName = last;
    }
    var myFather = new Person("John", "Doe");

    NaN: not a legal number
    undefined: does not have value
    null: is empty, not pointing to memory address

    compare two javascript objects always return false

2. == and ===
  • never use ==
  • === compare 'type' and 'value' for primitive type
  • === compare 'reference' for complex type
  • == do type conversion before comparison

3. closure
  • closure is function with preserved scope data
  • closure is an (usually anonymous) inner function within a outer function
  • inner function access latest value of the outer function's variable
  • essence: function can always see the variable in scope when it's defined, if the variable is not global, it will not pollute namespace
      var add = (function () {
          var counter = 0;
          return function () {return counter += 1;}  
      })();

      /* add() is a function, where it searches for the 'counter' value via lexical scope chain till find it */

      add();   // 1
      add();   // 2
      add();   // 3

4. hoist
  • 'hoisted' means you can use it before declaring it
  • 'var' and function declaration are hoisted
  • 'let' and 'const' is not hoisted
  • always declare your variables at the top!
   
      function foo() {
          function bar() {
              return 3;
          }
          return bar();
          function bar() {
              return 8;
          }
      }
      alert(foo());      //8

      function foo(){
          var bar = function() {
              return 3;
          };
           return bar();
           var bar = function() {
                return 8;
           };
      }
      alert(foo());    //3

5. const
  • const is not const value but const reference
  • cannot reassign const value, array, object
  • can change element of const array, can change property of const object

6. function
  • javascript function is OBJECT!
  • first class function/object: language treat function as variable
  • high-order function: function that works on other function, i.e. can accept function as parameter, can return function as result

7. property
  • a free form object can add property any time
  • an object created from constructor can not add additional property
      function Person(first, last, age, eyecolor) {
          this.firstName = first;
          this.lastName = last;
          this.age = age;
          this.eyeColor = eyecolor;
      }
      Person.prototype.nationality = "English";


8. prototype chain
  • all javascript objects (including function) inherit property and method from prototype
  • 'prototype' allow you to add new property and method to constructor function
  • after prototype is changed, all newly created object will have the changed property value, all previously created object will have previous value
  • '__proto__' is the property of an object, pointing to its prototype

9. wait for ajax call to complete
  • it depends on how ajax call is implemented
  • if implemented in jquery, use jquery function

10. promise
  • implementation
      var promise = new Promise (function(resolve, reject) {
          // "producing code" (may take some time)

          if (/* everything turned out fine */) {
              resolve("stuff worked!");                      //return 'stuff worked!'
          }
          else {
              reject(Error("It broke"));                      //return Error('it broke')
          }
      }); 
  • usage
      promise.then (
          onFulfilled (result) {
              console.log(result);                             // "Stuff worked!"
          }, 
          onRejected (err) {
              console.log(err);                                 // Error: "It broke"
      });

      promise.catch (
          onRejected (err) {
              console.log(err);                                // Error: "It broke"
      });
  • function needs to return a promise to be able to use .then()

11. arrow function (arguments on the left, return type on the right)
   
      (param1, param2, …, paramN) => { statements }
      (param1, param2, …, paramN) => expression          // equivalent to: => { return expression; }
      singleParam => { statements }
      () => { statements }
      params => ({foo: bar})

      const multiplyES6 = (x, y) => { return x * y };
      (id, name) => ({ id: id, name: name });

      var MakePoint: () => {x: number; y: number;};  //function declaration, not definition
      var MakePoint = () => 1;   //function definition

12. scope
  • global scope
  • function scope and block scope
  • 'var' has functional scope
  • 'let' and 'const' has block scope
  • declare variable at beginning of script
      for (var i=0; i<10; i++) {
          // block scope for the for statement
      }
      console.log(i) // => 10

      for (let i=0; i<10; i++) {
          // block scope for the for statement
      }
      console.log(i) // ReferenceError: i is not defined
  • closure: outer function variable visible in inner function

13. context vs scope
  • context is the value of 'this' when function is called
  • scope is how javascript resolve a variable at run time

14. this
  • in regular function 'this' refer to current context (the object that calls the function)
  • in arrow function 'this' will always be the context when function is initially defined
  • closure can not access outer function's 'this'
      var person = {
          name: "John",
          getName : function() {
              return this.name;
          }
      };
      person.getName();  //John, 'this' refer to person

      var person = {
          name: "John",
          getName : () => {
              return this.name;
          }
      };
      person.getName();  //window.name, 'this' refer to window

      function Person(name) {
          this.name = name;
          this.getName = () => {
              return this.name;
          }
      }
      person = new Person('Mike');
      person.getName(); //Mike


15. curried function
  • transform a function from f(a, b, c) to f(a) (b) (c)
  • equivalent curried function: let add = x => y => x + y;

16. callback

      function getWidthOfImage(src) {
          var imgWidth;

          var img = document.createElement('img');
          img.onload = function() {
              imgWidth = this.width;             //async call
          };
          return imgWidth;                          //return 'undefined'
      }

      var width = getWidthOfImage('lolcat.png');
      alert(width);

      function getWidthOfImage(src, cb) {   
          var img = document.createElement('img');
          img.onload = function() {
              cb(this.width);
          };
      }

      getWidthOfImage('lolcat.png', function (width) {
          alert(width);                                  //using callback
      });

17. var vs let, const
  • var is scoped to the nearest function scope
  • let, const is scoped to the nearest block scope
  • use 'let' if you'll reassign value
  • use 'const' unless you'll reassign value
  • never use 'var'

18. common function
  • map() create a new array when calling a function on current array
  • splice() insert item into array at specified index
  • split() split a string into an array of substrings
  • slice(begin, end) return part of the string

19. ...
  • rest operatunor: get the argument list passed to function
      function countArguments(...args) {  
          return args.length;
      }

20. async and await
  • async function returns a promise
  • you can use await with any function that returns a promise (not necessarily async) 
  • you should use async function ONLY when you use await inside the function
  • makes it easier to use common programming constructs like return and try/catch
  • await won't work in the top level code

21. catch error for promise
  • use asyn/await
  • ending promise chain with catch()
save()
  .then(
    handleSuccess,
    handleNetworkError
  )
  .catch(handleProgrammerError)
;


22. generator and yield
  • generator return an iterator
  • each call to the iterator's next() function return the next step
  • each step's value is the value specified by yield

23. IIFE
  • does not pollute global namespace
(function() {
  /* */
  return {}          //return object literal
})()


24. shallow copy vs deep copy
  • primitive type: pass value
  • structural type: pass reference
  • shallow copy does not work with nested objects

25. optional access operator
  • ?      // optional chaining, if object is undefined or null, it will short circuit to undefined instead of throwing error

reference
1. javascript closure
2. javascript promise
3. how javascript promise works
4. understand javascript this
5. understanding javascript closure
6. ES6 arrow functions
7. typescript deep dive
8. javascript scope and context
9. when to use arrow function
10. call back, promise and async await
11. the modern javascript tutorial
12. javascript scope and closures
13. function scope and block scope
14. catch error in javascript promise
14. arrow function
15. javascript inheritance
16, top javascript to learn 2017
17. promise resolve and reject
18. From JavaScript Promises to Async/Await: why bother?
19. javascript generators: understanding them
20. the basics of javaScript generators
21. the modern javascript tutorial
22. need to return a promise to be used by then()
23. javascript inheritance pattern
24. 6-advanced-javascript-techniques-you-should-know
25. 23 advanced javascript interview questions
26. javascript.info async-await

Monday, 5 June 2017

algorithm

1. tree traversal
  • depth-first-search, use stack
  1. pre-order: root, left, right
  2. in-order: left, root, right
  3. post-order: left, right, root
  • breadth-first-search, use queue
  1. level-order: 1st level, 2nd level

2. pre-order
  • check if root is empty or null
  • display(root->data)
  • preorder(root->left)
  • preorder(root->right)

3. inorder
  • check if root is empty or null
  • inorder(root->left)
  • display(root->data)
  • inorder(root->right)

4. post-order
  • check if root is empty or null
  • postorder(root->left)
  • postorder(root->right)
  • display(root->data)

5. coding interview
  • 'null' check
  • use 'sorting'
  • use 'map'
  • use 'two index pointer'

6. two sum

    problem:
        find indices of two numbers such that they add to specific target value
        e.g. given nums = [2, 7, 11, 15], target = 9

    solution:
         1. use hashmap, while iterate array, store (9's complement of a[i], i)  to map, search map
         2. 双指针,一头一尾,sum小移头,sum大移尾

7. binary search
  • edge case 1: array==null || array.length ==0
  • edge case 2: target < min(array) || target > max(array)
  • edge case 3: if it is not a perfect match, found index diff by either +1 or -1
    int binarySearch (int[] nums, int target){
        if (nums == null || nums.length == 0)
            return -1;

        int left = 0, right = nums.length - 1;

        while(left < right){
            // Prevent (left + right) overflow
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) { return mid; }
            else if (nums[mid] < target) { left = mid + 1; }
            else { right = mid - 1; }
        }

        // End Condition: left > right
        return -1;
}

8. binary search tree

    public static boolean contains(Node root, int value) {
        if (root == null) {
            return false;
        } else if (root.value == value) {
                return true;
   
        } else if (value < root.value) {
            return contains(root.left, value);
        } else {
            return contains(root.right, value);
        }
    }

9. longest substring without repeating char
  • use hashmap to store existing char and index 
  • use sliding window to track current substring
  • if duplicate char is found, update sliding window to the right of duplicate

10. merge two sorted array

    input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6],       n = 3

    output: [1,2,2,3,5,6]

    public void merge(int a[], int m, int b[], int n) {
        int i = m - 1;
        int j = n - 1;
        int k = m + n - 1;

while (i >= 0 && j >= 0) {
            if (a[i] > b[j])
                a[k--] = a[i--];
            else
                a[k--] = b[j--];
            }
        while (j >= 0)
                a[k--] = b[j--];
    }

11. leetcode: https://www.youtube.com/watch?v=qg0CY00qJqI&list=PLi9RQVmJD2fYXgBAUfaN5MXgYPUTbzqeb&index=6


reference
1. cracking the coding interview.pdf
2. tree traversal, preorder, inorder, postorder
5. Steven Skiena's The Algorithm Design Manual.

Friday, 2 June 2017

rest-assured

1. getting started
  • place rest-assured before the JUnit dependency declaration in pom.xml
  • use statically import methods, i.e. 'import static io.restassured.RestAssured.*;'

2. example

given().   // parameter
    contentType()
    param().
    formParam().
    queryParam().

when().   // action
    get().
    put()
    post().

then().     // field
    body()
    statusCode()

assertion  // locator + matcher

locator
--------
lotto.lottoId
lotto.winners.winnerId

find { it.@type == 'groceries' }  //Groovy

hamcrest matchers
-----------------------
is
equalTo
hasItems
hasXPath
matchesXsd
matchesJsonSchemaInClasspath
matchesXsd

    {
        "lotto":{
            "lottoId":5,
            "winning-numbers":[2,45,34,23,7,5,3],
            "winners":[
               {
                    "winnerId":23,
                    "numbers":[2,45,34,23,3,5]
                },
               {
                    "winnerId":54,
                    "numbers":[52,3,12,11,18,22]
                }
             ]
        }
    }


3. pass parameters

    given().                                           //'get' will automatically convert param to query
        param("param1", "value1").
    when().
        get("/something");

    given().                                           //'post' and 'put' user will hava choice
        formParam("formParamName", "value1").
        queryParam("queryParamName", "value2").
    when().
        post("/something");


4. others
  • log().all()
  • request.relaxedHTTPSValidation()

5. multipart/form data 
  • multipart -> multiPart (file)
  • form data -> formParam (json, name value pair)

6. link in rest-assured/SSLITest.java for example on using of certificate

7. link for client certificate example on using .jks as truststore and .p12 as keystore

8. two ways to parse json response and 1 way to reconstruct into json

    Map responseBody = RestAssuredClientFactory.responseToObject(response, Map)
    assert responseBody.BSBResponse.BSBName

    @Step("Map response to generic Object")
    public static <T> T responseToObject(Response response, Class<T> responseType) {
        return response.getBody().as(responseType);
    }

   or 
   
   response.jsonPath().get("results[0].data.type")

   then 
   new JsonBuilder(payload).toPrettyString()


9. do not use default charset in content header

RestAssured.config =
    RestAssured.config().encoderConfig(
            RestAssured.config().encoderConfig
                    .appendDefaultContentCharsetToContentTypeIfUndefined(false))


10. create json payload

ObjectMapper objectMapper = new ObjectMapper()
        def payload = [
                assetId: assetId,
                udid: playerEnum.udid
        ]
objectMapper.writeValueAsString(payload)


11. package io.restassured.path.json
      public class JsonPath {}
      can be used to parse json STRING in general


12. use jackson to change json file value

import com.fasterxml.jackson.databind.ObjectMapper
String path = FileSystem.getResourcePath(fileName)
Map map = objectMapper.convertValue(loadFile(path), Map)   //convert from jsonNode to map
map.channel.name = channelName                                             //change value
objectMapper.writeValueAsString(map)                                     //convert back to json

static JsonNode loadFile(String file) {
    InputStream fileStream = new FileInputStream(file)
    objectMapper.readValue(fileStream, JsonNode)
}


13. groovy define json payload 

def payload = [records: []]
payload.records << [
        key  : [
                channelName: playList.channelName,
                origin     : playList.origin
        ],
        value: [
                channel: [
                        name   : playList.channelName,
                        enabled: false
                ],
                date   : playList.playlistDate
]

protractor

1. install nodejs

2. install protractor and start selenium server
  •     npm install -g protractor
  •     webdriver-manager update
chromedriver version which protractor uses for tests executing depends on version in node_modules/protractor
npm update protractor - update protractor to latest version
webdriver-manager update - update chrome driver to latest version
  •     webdriver-manager start

3. run protractor
  •     protractor conf.js

4. angular locator
  •     browser.getTitle()
  •     by.model
  •     by.id
  •     by.binding
  •     by.repeater

5. webdriverjs is asynchronous
  • by default it return promise
  • .then() is called when promise is 'fulfilled', .catch() is called when promise is 'rejected
  • 'control flow' ensure async tasks executed and completed in the correct order 

6. framework
  • by default, protractor use jasmine
  • cucumber is no longer included
  • it also support mocha and cucumber, cucumber is prefered

7. exports.config = {
        seleniumAddress: "http://127.0.0.1:4444/wd/hub",
        baseUrl: "localhost:8080"
}
  • used for globals variables and configuation of test

8. webdriver control flow
  • most webdriver actions are asynchronous
  • to synchroize, use either 'control flow', 'promise chain' or 'async/await'
  • control flow makes sure commands are executed in the order they were received
  • protractor will wait until control flow is empty before deeming a test finished

9. protractor click method on anchor is not working
  • browser.executeScript("arguments[0].scrollIntoView();", e.getWebElement());
  • browser.executeScript("arguments[0].click();", e.getWebElement());

10. protractor-cucumber-framework

11. 'defineSupportCode' is depreciated in cucumber
  • use 'import {Given,Then,When} from "cucumber";'
  • use 'import {setWorldConstructor} from 'cucumber''

12. debug in vscode
  • add configuration
  • specify 'program' and 'args'
            "args":["${workspaceFolder}/protractor.conf.js"],
            "program": "${workspaceFolder}/node_modules/protractor/bin/protractor"
  • node_modules/protractor/bin/webdriver-manager update
  • webdriver-manager start before debug
  • kill -9 $(lsof -ti tcp:4444)

13. cucumber (gherkin) full support plugin
  • setting.json in .vscode folder to specify feature/step mapping


reference:
1. install nodejs in windows
2. protractor tutorial
3. enqueue non-promise statement into control flow
4. protractor-cucumber-framework
5. protractor-vs-webdriverio-vs-nightwatch
6. in depth protractor tutorial
7. protractor not working on anchor
8. webdriver control flow
9. return promise in protractor-cucumber-framework step function
10. defineSupportCode is not supported in cucumber
11. how to use setWorldConstructor
12. debug protractor in vscode
13. “could not find update-config.json” error message