-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.json
1 lines (1 loc) · 35.9 KB
/
content.json
1
{"meta":{"title":"Mason's blog","subtitle":null,"description":null,"author":"Mason Shin","url":"https://minsooshin.github.io"},"pages":[],"posts":[{"title":"Code Convention Tooling for Better Collaboratation","slug":"Code-Convention-Tooling-for-Better-Collaboratation","date":"2017-05-18T20:14:53.000Z","updated":"2017-05-19T04:15:53.000Z","comments":true,"path":"2017/05/18/Code-Convention-Tooling-for-Better-Collaboratation/","link":"","permalink":"https://minsooshin.github.io/2017/05/18/Code-Convention-Tooling-for-Better-Collaboratation/","excerpt":"If you have worked at any size of company before or now, you have had the difficulty about inconsistent code styles to work with. I have worked at a company which has front-end code based on Rails platform. At that time, it was really diffult to have code convention tools for front-end. So, whenever someone has pull request to get review, other engineers need to make a comment on each code convention issue. Obviously, there were some struggling about those comments since it doesn’t affect on the performance at all, it just style preference, and it cannot be agreed from all of the engineering team sometimes. In that situation, some engineers ignore the comment and merge their pull request without applying it, and it can be a critical communication issue. Fortunately, the architect team decided to move on to node.js platform for front-end, and we could introduce code convention tools for entire JavaScript code. Then, integrated with CI tool, jenkins, to run lint testing whenever there is new pull request created. I would like to share how to set up the linter tool for JavaScript code base application, and how to integrate with Travis CI for your personal projects on Github.","text":"If you have worked at any size of company before or now, you have had the difficulty about inconsistent code styles to work with. I have worked at a company which has front-end code based on Rails platform. At that time, it was really diffult to have code convention tools for front-end. So, whenever someone has pull request to get review, other engineers need to make a comment on each code convention issue. Obviously, there were some struggling about those comments since it doesn’t affect on the performance at all, it just style preference, and it cannot be agreed from all of the engineering team sometimes. In that situation, some engineers ignore the comment and merge their pull request without applying it, and it can be a critical communication issue. Fortunately, the architect team decided to move on to node.js platform for front-end, and we could introduce code convention tools for entire JavaScript code. Then, integrated with CI tool, jenkins, to run lint testing whenever there is new pull request created. I would like to share how to set up the linter tool for JavaScript code base application, and how to integrate with Travis CI for your personal projects on Github. Setup RepositoryAs for now, Eslint is the most popular tool for linting the JavaScript code, so I will introduce it to validate the JavaScript code convention. Let’s set up a repository for this example. Once you created the repository, let’s clone it on your local machine. 12$ git clone [email protected]:minsooshin/codeConventionTooling.git$ cd codeConventionTooling Install PackagesFor this example, we will need some modules to run our application. 1234567$ yarn init # or npm init$ yarn add --dev babel-core$ yarn add --dev babel-plugin-transform-object-rest-spread$ yarn add --dev babel-preset-es2015$ yarn add --dev eslint$ yarn add --dev eslint-friendly-formatter$ yarn add --dev eslint-watch I add one by one to show which packages are needed, you can do this with one line command. Once you installed the packages, your package.json file will look like this. 12345678910111213141516171819{ \"name\": \"codeConventionTooling\", \"version\": \"0.0.1\", \"description\": \"code convention tooling example\", \"main\": \"index.js\", \"repository\": \"[email protected]:minsooshin/codeConventionTooling.git\", \"author\": \"Mason Shin <[email protected]>\", \"license\": \"MIT\", \"devDependencies\": { \"babel-core\": \"^6.24.1\", \"babel-plugin-transform-object-rest-spread\": \"^6.23.0\", \"babel-preset-es2015\": \"^6.24.1\", \"eslint\": \"^3.19.0\", \"eslint-config-airbnb-base\": \"^11.2.0\", \"eslint-friendly-formatter\": \"^3.0.0\", \"eslint-plugin-import\": \"^2.2.0\", \"eslint-watch\": \"^3.1.0\" }} Set babel configurationTo use ES6 syntax, let’s create .babelrc file under the project root directory. Then, add these lines.1234{ \"presets\": [\"es2015\"], \"plugins\": [\"transform-object-rest-spread\"]} Initiate EslintNow, we can setup our eslint configuration with installed package. Run this command on your terminal.1$ ./node_modules/.bin/eslint --init It will propmt this question to you.1234? How would you like to configure ESLint?❯ Answer questions about your style Use a popular style guide Inspect your JavaScript file(s) Select Use a popular style guide, then next question will be this.1234? Which style guide do you want to follow? (Use arrow keys)❯ Google Airbnb Standard I use Airbnb most of cases. So, I will select Airbnb, then next.1? Do you use React? (y/N) If you are creating React app, then type y, but I will type N in this example since I am not creating React app. Then, you will see the last question. 1234? What format do you want your config file to be in? (Use arrow keys)❯ JavaScript YAML JSON I am using JavaScript format for the eslintrc, so it will generate .eslintrc.js file for me. NPM ScriptsAs you know, we need to set up the npm scripts to execute our expected behaviors in the package.json. Open the package.json file, and add "scripts" property above the "devDependencies". 123\"scripts\": { \"eslint\": \"./node_modules/.bin/eslint src --ext .js\"}, Once you have this in your package.json file, you can validate your JavaScript files under src directory with yarn run eslint command. If you are using npm, then use npm instead of yarn. Example CodeI will create an JavaScript file which exports simple funciton returns the input array has duplicates or not. 12345678910111213141516// src/containsDuplicate.js/** * @param {number[]} nums * @return {boolean} */export default function containsDuplicate (nums) { const seen = new Set() for (let i = 0; i < nums.length; i++) { if (seen.has(nums[i])) { return true } else { seen.add(nums[i]) } } return false} Once you saved this file, let’s execute the command for validate code.1$ yarn run eslint You will get this result from the command.12345678910111213yarn run v0.24.4$ ./node_modules/.bin/eslint src --ext .js/Users/mshin/Workspace/github/codeConventionTooling/src/containsDuplicate.js 5:42 error Unexpected space before function parentheses space-before-function-paren 6:25 error Missing semicolon semi 7:36 error Unary operator '++' used no-plusplus 9:18 error Missing semicolon semi 10:12 error Unnecessary 'else' after 'return' no-else-return 11:24 error Missing semicolon semi 14:15 error Missing semicolon semi✖ 7 problems (7 errors, 0 warnings) Each error has the error name on it, so you can find out what the error is for from the Eslint website. If you don’t want to have the rule which is Airbnb based, you can disable it by adding the rule disabling in the .eslintrc.js file. For example, I usually don’t use semicolon(;) at the end of the line, so I will add this in my .eslintrc.js. The reason why I don’t use semicolon in my code is when I compile the production package, it can be automatically add semicolons. 123'rules': { 'semi': [2, 'never'] // this is equivalent to 'semi': ['error', 'never']} Let’s try again our command for validate code. Now, we will get this.123456789yarn run v0.24.4$ ./node_modules/.bin/eslint src --ext .js/Users/mshin/Workspace/github/codeConventionTooling/src/containsDuplicate.js 5:42 error Unexpected space before function parentheses space-before-function-paren 7:36 error Unary operator '++' used no-plusplus 10:12 error Unnecessary 'else' after 'return' no-else-return✖ 3 problems (3 errors, 0 warnings) So, all the semicolon issues are gone. Woohoo!! Let’s take a look at the no-plusplus issue. That ++ unary operator is used in the for loop, and it is quite common usage, so I wouldn’t like to change my code due to this error. I will add this line to .eslintrc.js based on the instruction of no-plusplus rule page. 1\"no-plusplus\": [2, { \"allowForLoopAfterthoughts\": true }] If you want to keep the default rule and only ignore on a file, then you can disable the rule on specific error. 123/* eslint-disable no-plusplus */for (let i = 0; i < nums.length; i++) {/* eslint-enable */ Let’s fix other two errors in the code, not updating rules. Finally, we get this result from our validation.123yarn run v0.24.4$ ./node_modules/.bin/eslint src --ext .js✨ Done in 0.68s. And the final our containsDuplicate.js file looks like this:12345678910export default function containsDuplicate(nums) { const seen = new Set() for (let i = 0; i < nums.length; i++) { if (seen.has(nums[i])) { return true } seen.add(nums[i]) } return false} How easy it is!!! Let’s commit changes to move on to Travis CI integration. Travis CIGithub supports integration with Travis CI only for the public repositories. So, your repository should be public to use Travis CI for free. Before the integration, please sign up the Travis CI with your Github here. Once you log in Travis CI, you will see this menu on the screen. Click on the + icon, then it will show all your Github repositories. Then, click the Sync account button at the top right corner of content, and turn on the codeConventionTooling repository for the CI. I will add the Travis CI badge to my repository to see more easily about the eslint status. Go to the repository’s Travis CI configuration by clicking the cog icon next to the repository name. Click the badge icon, then you will get a dialog box. Please select whatever you like as format. I usually use markdown format. Copy the contents in the textarea, then paste it to your README.md Next, we need to add a file to integrate the Travis CI with our repository. Create a file with .travis.yml name, and add these lines. 12345language: node_jsnode_js: - "6"script: - npm run eslint That is it! Once you commit your change, you will see the Travis CI is triggered. And if the code validation is succeeded, your commit will have green checkmark next to the commit message. Finally, you can see the Travis CI passing badge.","categories":[{"name":"tutorial","slug":"tutorial","permalink":"https://minsooshin.github.io/categories/tutorial/"}],"tags":[{"name":"JavaScript","slug":"JavaScript","permalink":"https://minsooshin.github.io/tags/JavaScript/"},{"name":"Eslint","slug":"Eslint","permalink":"https://minsooshin.github.io/tags/Eslint/"},{"name":"React","slug":"React","permalink":"https://minsooshin.github.io/tags/React/"}]},{"title":"React Fiber: 사실에 입각한 루머 정리","slug":"React-Fiber-Reconciling-the-Rumours-with-the-Facts","date":"2017-05-11T16:29:34.000Z","updated":"2017-05-21T22:47:03.000Z","comments":true,"path":"2017/05/11/React-Fiber-Reconciling-the-Rumours-with-the-Facts/","link":"","permalink":"https://minsooshin.github.io/2017/05/11/React-Fiber-Reconciling-the-Rumours-with-the-Facts/","excerpt":"최근 자바스크립트 프레임워크들이 당신이 주로 다루는 것이라면, 아마도 최근들어 사람들이 React Fiber 에 대해서 이야기 하는 것을 들어봤을 것 입니다. React 의 “다음 버전”을 학수 고대하고 그것을 적용하여 당신의 앱들을 모던 앱의 가볍고 빠르게 변화시키고 싶을지도 모릅니다. 또 한편으로 좌절감이 느껴질 정도로 빠른 자바스크립트 프레임워크들의 발생, 진화, 소멸의 속도를 보면, 이 Fiber 도 당신에게 극심한 혼돈을 야기할 수도 있습니다. 자, 심호흡 한 번 하시고 이제 시작하겠습니다. 이 글의 목적은 당신을 조금이라도 안도하게 하고 Fiber 에 관한 잘못된 상식들을 바로 잡고자 함입니다.","text":"최근 자바스크립트 프레임워크들이 당신이 주로 다루는 것이라면, 아마도 최근들어 사람들이 React Fiber 에 대해서 이야기 하는 것을 들어봤을 것 입니다. React 의 “다음 버전”을 학수 고대하고 그것을 적용하여 당신의 앱들을 모던 앱의 가볍고 빠르게 변화시키고 싶을지도 모릅니다. 또 한편으로 좌절감이 느껴질 정도로 빠른 자바스크립트 프레임워크들의 발생, 진화, 소멸의 속도를 보면, 이 Fiber 도 당신에게 극심한 혼돈을 야기할 수도 있습니다. 자, 심호흡 한 번 하시고 이제 시작하겠습니다. 이 글의 목적은 당신을 조금이라도 안도하게 하고 Fiber 에 관한 잘못된 상식들을 바로 잡고자 함입니다. Fiber는 무엇인가?먼저, Fiber 가 아닌 것부터 짚고 넘어가야 합니다. Fiber 는 새로운 프레임워크가 아니고 React 에 망가진 API를 야기하기도 않습니다. 다시 말하지만, Fiber 는 어떠한 API도 망가뜨리지 않습니다. 대신, React Fiber 는 React 의 핵심 알고리즘을 분해해서 새로 쓴 것입니다. 비록 React 의 외부 API가 React 팀으로 하여금 좋은 기능들(render로 부터 배열을 반환할 수 있는 것과 같은)을 추가할 수 있게 해주지만, Fiber 는 React 의 내부적인 작동방식을 바꾼 것이지, React 의 외부 API를 바꾼 것이 아닙니다. 작동원리React Fiber 는 React 의 조정자를 다시 쓴 것입니다. React 에서, 조정자는 virtual DOM의 차이점 구별과 업데이트를 담당합니다. 이는 페이지에 나타내는 renderer로 virtual DOM을 보내기 전에 그것들을 업데이트합니다. 이 조정자를 renderer로 부터 독립시킴으로써 React 가 다른 플랫폼(예: React Native)을 목표로 하는 renderer들과도 작동할 수 있게 하는 것입니다. 현재 React 버전에서는, 컴포넌트가 업데이트되면, 조정자는 그 컴포넌트의 내부 표현을 업데이트하고 그 업데이트된 내용을, 실제 DOM을 다시 표현하는, renderer에게 보냅니다. 이 과정은 변경 사항이 실행될 때까지 전체 트리를 통해 계속 진행되며, 모든 업데이트과 필요한 모든 렌더링을 한 번씩 수행합니다. 이와 같은 오래 지속되는 자바스크립트 프로세스의 문제점은 브라우저가 다른 것을 못하게 막는다는 것입니다. 만약, 이 프로세스가 매우 오래 걸리면, 프레임은 버려지고, 렌더링은 질도 떨어지고 느려지게 됩니다. Fiber 라 불리우는 새로운 조정자는 각 엘리먼트의 업데이트를 한 번에 하나씩 처리하고, 다음 엘리먼트로 넘어가기 전에 브라우저가 필요한 모든 작업(사용자 상호작용, 레이아웃, re-render 및 garbage collection)을 수행 할 수도 있도록 해줍니다. Fiber 조정자는 renderer에게 더이상 각 엘리먼트의 업데이트를 보내지 않습니다. 업데이트들을 work-in-progress 트리라 알려진 또다른 virtual DOM에 저장합니다. 이 work-in-progress 트리는 특정 변화들을 계속 기록 합니다. 전체적인 트리가 준비가 되었을 때만, renderer에게 그 업데이트들을 보냅니다. Fiber 는 또한 인식된 성능의 중요도에 따라 업데이트의 우선 순위를 결정합니다. 매우 중요한 업데이트는 바로 실행합니다. 다른 업데이트들은 스케쥴을 잡고, 브라우저가 그 일을 수행할 여유가 있을 때 실행합니다. 만약 상위 우선 순위의 업데이트가 우선 순위가 낮은 다른 업데이트들이 끝나기 전에 예약 되면, 이전 업데이트가 어셈블링 중인 work-in-progress 트리가 삭제되고 다시 시작됩니다. 애니메이션과 같은 중요한 업데이트는 인지된 성능에 덜 중요한 업데이트를 기다릴 필요가 없습니다. Fiber는 내가 가지고 있는 앱을 망가뜨리는가?간단히 말하면, 아닙니다. React 팀은 이미 현존하는 많은 앱들을 망가뜨릴 수 있는 API 변화를 릴리즈 하지 않기 위해서 매우 조심하고 있다. 보통 그들은 API가 실제로 코드에서 삭제되기 몇 버전 전부터 알림을 추가한다. 심지어 개발자들이 최근 버전으로 바꿀 수 있도록 도와주는 스크립트를 제공합니다. 페이스북은 이미 그들의 3만개 이상의 컴포넌트에서(페이스북은 Fiber 를 사용중이다) 테스트된 Fiber 를 가지고 있다. React v16에서 약간의 deprecation들이 있을 것이지만 Fiber 와는 무관하다. 만약 당신의 앱이 deprecation 알림 없이 v15.5에서 작동한다면, v16을 쓸 준비가 이미 된 것입니다. Fiber가 나에게 주는 이점은?일례로, Fiber 는 당신의 앱이 60fps로 부드럽게 작동하게 해 줄 것입니다. Fiber 는 또한 오래 지속되었던 문제들을 정리 해줍니다. 목표 중에 하나가 새로은 기능을 추하고 고유의 renderer를 작성하기 쉽게 하는 것입니다. 언제 릴리즈 되나?공식적인 Fiber 릴리즈 날짜는 없습니다. React v16 은 “공존 가능 모드(비동기 기능이 비활성화 됨을 의미)”로 Fiber 를 작동시킬 것입니다. 버전 17은 완벽히 Fiber 를 작동시킬 것입니다, 하지만 현재로써는 언제 나올지는 알 수 없습니다. 그래도 굳이 쓰고 싶다!버전 정보를 명시함으로써 React v16 을 설치 할 수 있습니다.1yarn add [email protected] 또는, 정말 원한다면 React 소스를 다운받고 여기에 있는 안내를 따라서 직접 만들어 볼 수 있습니다. Fiber 는 아직 개발중입니다, 그러니 부디 주의를 기울여 주십시오. 원문: http://blog.rangle.io/react-fiber-reconciling-the-rumours-with-the-facts/","categories":[{"name":"news","slug":"news","permalink":"https://minsooshin.github.io/categories/news/"}],"tags":[{"name":"JavaScript","slug":"JavaScript","permalink":"https://minsooshin.github.io/tags/JavaScript/"},{"name":"React","slug":"React","permalink":"https://minsooshin.github.io/tags/React/"}]},{"title":"Find All Duplicates in an Array","slug":"Find-All-Duplicates-in-an-Array","date":"2017-05-08T16:38:22.000Z","updated":"2017-05-08T18:16:55.000Z","comments":true,"path":"2017/05/08/Find-All-Duplicates-in-an-Array/","link":"","permalink":"https://minsooshin.github.io/2017/05/08/Find-All-Duplicates-in-an-Array/","excerpt":"","text":"Source: leetcode 442. Find All Duplicates in an Array Q. Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example:Input: [4, 3, 2, 7, 8, 2, 3, 1]Output: [2, 3] Answer123456789101112131415/** * @param {number[]} nums * @return {number[]} */export default function findDuplicates (nums) { const res = [] for (let i = 0; i < nums.length; i++) { const id = Math.abs(nums[i]) - 1 if (nums[id] < 0) { res.push(id + 1) } nums[id] = -nums[id] } return res}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"array","slug":"array","permalink":"https://minsooshin.github.io/tags/array/"},{"name":"medium","slug":"medium","permalink":"https://minsooshin.github.io/tags/medium/"}]},{"title":"Convert Sorted Array to Binary Search Tree","slug":"Convert-Sorted-Array-to-Binary-Search-Tree","date":"2017-05-05T04:50:20.000Z","updated":"2017-05-05T07:00:49.000Z","comments":true,"path":"2017/05/04/Convert-Sorted-Array-to-Binary-Search-Tree/","link":"","permalink":"https://minsooshin.github.io/2017/05/04/Convert-Sorted-Array-to-Binary-Search-Tree/","excerpt":"","text":"Source: leetcode 108. Convert Sorted Array to Binary Search Tree Q. Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Answer12345678910111213141516171819202122232425/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * @param {number[]} nums * @return {TreeNode} */export default function sortedArrayToBST (nums) { if (!nums.length) return null function helper(nums, low, high) { if (low > high) { return null } const mid = (low + high) / 2 | 0 const node = new TreeNode(nums[mid]) node.left = helper(nums, low, mid - 1) node.right = helper(nums, mid + 1, high) return node; } return helper(nums, 0, nums.length - 1)}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"easy","slug":"easy","permalink":"https://minsooshin.github.io/tags/easy/"},{"name":"tree","slug":"tree","permalink":"https://minsooshin.github.io/tags/tree/"},{"name":"dfs","slug":"dfs","permalink":"https://minsooshin.github.io/tags/dfs/"}]},{"title":"Asynchronous JavaScript with async/await","slug":"Asynchronous-JavaScript-with-async-await","date":"2017-05-04T04:37:32.000Z","updated":"2017-05-04T20:19:17.000Z","comments":true,"path":"2017/05/03/Asynchronous-JavaScript-with-async-await/","link":"","permalink":"https://minsooshin.github.io/2017/05/03/Asynchronous-JavaScript-with-async-await/","excerpt":"1. Write an Asynchronous Function with async/awaitHere, we have short function that talks with a github API. 12345678910111213const fetch = require('node-fetch')function showGithubUser(handle) { const url = `https://api.github.com/users/${handle}` fetch(url) .then(resp => resp.json()) .then(user => { console.log(user.name) console.log(user.location) })}showGithubUser('minsooshin') It loads a specific user, and once the response comes back, it parses the body as JSON. Finally, user’s name and location are logged to the console.","text":"1. Write an Asynchronous Function with async/awaitHere, we have short function that talks with a github API. 12345678910111213const fetch = require('node-fetch')function showGithubUser(handle) { const url = `https://api.github.com/users/${handle}` fetch(url) .then(resp => resp.json()) .then(user => { console.log(user.name) console.log(user.location) })}showGithubUser('minsooshin') It loads a specific user, and once the response comes back, it parses the body as JSON. Finally, user’s name and location are logged to the console. Let’s see how we can convert this function into asynchronous function by using the async and await keywords. Make the function asynchronous by adding the async keyword. Using the await operator to wait until the fetch call complete. The await operator takes a promise and pause the function execution until the promise is settled. Assign the return value from await operator to a variable. Take the body of the response and parse it as JSON. Print out the result. 1234567891011const fetch = require('node-fetch')async function showGithubUser(handle) { const url = `https://api.github.com/users/${handle}` const resp = await fetch(url) const user = await resp.json() console.log(user.name) console.log(user.location)}showGithubUser('minsooshin') To use this async/await, please user node 7.6 or up. 2. Call an Asynchronous Function in a Promise ChainNow, showGithubUser function fetches the user from the github API, and then prints the name and location to the console. Let’s refactor this program such that the function only retrieves the user and returns to the caller who can decide what to do with it. Get rid of the console.log lines and just return the user; the showGithubUser is called, it returns the promise. We can build a promise chain with the .then method. 12345678910111213const fetch = require('node-fetch')async function fetchGithubUser(handle) { const url = `https://api.github.com/users/${handle}` const resp = await fetch(url) return await resp.json()}fetchGithubUser('minsooshin') .then(user => { console.log(user.name) console.log(user.location) }) This example shows that it is quite easy to call an asynchronous function as part of a promise chain. Every async function returns a promise, so you can simply call .then and .catch of the return value. 3. Convert Any Function into an Asynchronous FunctionJavaScript allows us to convert any function into an async function. So far, we’ve worked function declaration, but we haven’t yet looked at function expressions, arrow functions, or methods. Let’s convert this function declaration into a function expression. Cut the name, fetchGithubUser, and introduce a variable and then assign the function expression. 1234567891011121314151617const fetch = require('node-fetch')// function expressionconst fetchGithubUser = async function (handle) { const url = `https://api.github.com/users/${handle}` const resp = await fetch(url) return await resp.json()}// arrow function// const showGithubUser = async function (handle) => {fetchGithubUser('minsooshin') .then(user => { console.log(user.name) console.log(user.location) }) Let’s look at a good use case for an asynchronous function expression. The await keyword only be used in an asynchronous functions, so we cannot use it at the top level of the file. 1234567891011// this code doesn't workconst user = await fetchGithubUser('minsooshin')console.log(user.name)console.log(user.location)// to fix, wrap with `async`(async function() { const user = await fetchGithubUser('minsooshin') console.log(user.name) console.log(user.location)})() Finally, let’s implement asynchronous class method. define a class with GithubApiClient name. define a method to fetch user data. put async keyword in front of the method. create an instance of the class call the method with using the instance 12345678910111213141516const fetch = require('node-fetch')class GithubApiClient { async fetchUser (handle) { const url = `https://api.github.com/users/${handle}` const resp = await fetch(url) return await resp.json() }}(async function () { const client = new GithubApiClient() const user = await client.fetchUser('minsooshin') console.log(user.name) console.log(user.location)})() 4. Handle Errors in Asynchronous functionsLet’s use the example from section 2. What happens if we tried to load a user that doesn’t actually exist? If you run the program you will get this. Let’s see what the response object looks like. We will log out the user instead of individual property. Our fetchGithubUser function always returns a promise which resolve this value. This is not what we want. Instead, we want to reject this promise with error message. Store the return value of the JSON to the variable If the status of the response is not successful, throw an error Add catch method to our promise chain 12345678910111213141516171819202122const fetch = require('node-fetch')async function fetchGithubUser(handle) { const url = `https://api.github.com/users/${handle}` const resp = await fetch(url) const body = await resp.json() if (resp.status !== 200) { throw Error(body.message) } return body}fetchGithubUser('minsooshin') .then(user => { console.log(user.name) console.log(user.location) }) .catch(err => { console.log(`Error: ${err.message}`) }) This approach works because asynchronous function will automatically return a rejected promise whenever an error is thrown. This is what we can simply write a catch method and then deal with a rejected promise.Another advantage of async/await keywords is that we can use regular try/catch statement. This is not possible plain promises because the callback function is always invoked asynchronously. To illustrate how async/await is combined with try/catch blocks, convert promise chain into asynchronous function Add regular try/catch statement 1234567891011121314151617181920212223const fetch = require('node-fetch')async function fetchGithubUser (handle) { const url = `https://api.github.com/users/${handle}` const resp = await fetch(url) const body = await resp.json() if (resp.status !== 200) { throw Error(body.message) } return body}async function showGithubUser (handle) { try { const user = fetchGithubUser(handle) console.log(user.name) console.log(user.location) } catch (err) { console.log(`Error: ${err.message}`) }}","categories":[{"name":"tutorial","slug":"tutorial","permalink":"https://minsooshin.github.io/categories/tutorial/"}],"tags":[{"name":"JavaScript","slug":"JavaScript","permalink":"https://minsooshin.github.io/tags/JavaScript/"},{"name":"ES7","slug":"ES7","permalink":"https://minsooshin.github.io/tags/ES7/"}]},{"title":"Search Insert Position","slug":"Search-Insert-Position","date":"2017-05-03T20:29:37.000Z","updated":"2017-05-04T00:05:25.000Z","comments":true,"path":"2017/05/03/Search-Insert-Position/","link":"","permalink":"https://minsooshin.github.io/2017/05/03/Search-Insert-Position/","excerpt":"","text":"Source: leetcode 35. Search Insert Position Q. Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples.[1, 3, 5, 6], 5 → 2[1, 3, 5, 6], 2 → 1[1, 3, 5, 6], 7 → 4[1, 3, 5, 6], 0 → 0 Answer1234567891011121314151617181920/** * @param {number[]} nums * @param {number} target * @return {number} */export default function searchInsert (nums, target) { let low = 0 let high = nums.length - 1 while (low <= high) { const mid = (low + high) / 2 | 0 if (nums[mid] === target) { return mid } else if (nums[mid] > target) { high = mid - 1 } else { low = mid + 1 } } return low}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"easy","slug":"easy","permalink":"https://minsooshin.github.io/tags/easy/"},{"name":"array","slug":"array","permalink":"https://minsooshin.github.io/tags/array/"},{"name":"binary search","slug":"binary-search","permalink":"https://minsooshin.github.io/tags/binary-search/"}]},{"title":"Contains Duplicate","slug":"Contains-Duplicate","date":"2017-05-03T16:39:30.000Z","updated":"2017-05-04T00:05:11.000Z","comments":true,"path":"2017/05/03/Contains-Duplicate/","link":"","permalink":"https://minsooshin.github.io/2017/05/03/Contains-Duplicate/","excerpt":"","text":"Source: leetcode 217. Contains Duplicate Q. Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Answer123456789101112131415/** * @param {number[]} nums * @return {boolean} */export default function containsDuplicate (nums) { const seen = new Set() for (let i = 0; i < nums.length; i++) { if (seen.has(nums[i])) { return true } else { seen.add(nums[i]) } } return false}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"easy","slug":"easy","permalink":"https://minsooshin.github.io/tags/easy/"},{"name":"array","slug":"array","permalink":"https://minsooshin.github.io/tags/array/"},{"name":"hash table","slug":"hash-table","permalink":"https://minsooshin.github.io/tags/hash-table/"}]},{"title":"Reverse String","slug":"Reverse-String","date":"2017-05-03T16:22:02.000Z","updated":"2017-05-03T16:52:27.000Z","comments":true,"path":"2017/05/03/Reverse-String/","link":"","permalink":"https://minsooshin.github.io/2017/05/03/Reverse-String/","excerpt":"","text":"Source: leetcode 344. Reverse String Q. Write a function that takes a string as input and returns the string reversed. Example:Given s = “hello”, return “olleh” Answer 1: Using two pointers1234567891011121314/** * @param {string} s * @return {string} */export default function reverseString (s) { const arr = s.split('') const half = arr.length / 2 | 0 for (let i = 0; i < half; i++) { const temp = arr[i] arr[i] = arr[arr.length - i - 1] arr[s.length - i - 1] = temp } return arr.join('')} Answer 2: Using simple string concatenation1234567891011/** * @param {string} s * @return {string} */export default function reverseString (s) { let reversed = '' for (let i = s.length - 1; i >= 0; i--) { reversed += s.charAt(i) } return reversed}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"easy","slug":"easy","permalink":"https://minsooshin.github.io/tags/easy/"},{"name":"string","slug":"string","permalink":"https://minsooshin.github.io/tags/string/"},{"name":"two pointers","slug":"two-pointers","permalink":"https://minsooshin.github.io/tags/two-pointers/"}]},{"title":"Single Number","slug":"Single-Number","date":"2017-05-02T21:49:32.000Z","updated":"2017-05-03T16:52:36.000Z","comments":true,"path":"2017/05/02/Single-Number/","link":"","permalink":"https://minsooshin.github.io/2017/05/02/Single-Number/","excerpt":"","text":"Source: leetcode 136. Single Number Q. Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Answer 1: with using extra memory123456789101112131415/** * @param {number[]} nums * @return {number} */export default function singleNumber (nums) { const seen = new Set() for (let i = 0; i < nums.length; i++) { if (seen.has(nums[i])) { seen.delete(nums[i]) } else { seen.add(nums[i]) } } return seen.values().next().value} Answer 2: without using extra memory1234567/** * @param {number[]} nums * @return {number} */export default function singleNumber (nums) { return nums.reduce((curr, prev) => curr ^ prev)}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"easy","slug":"easy","permalink":"https://minsooshin.github.io/tags/easy/"},{"name":"hash table","slug":"hash-table","permalink":"https://minsooshin.github.io/tags/hash-table/"},{"name":"bit manipulation","slug":"bit-manipulation","permalink":"https://minsooshin.github.io/tags/bit-manipulation/"}]},{"title":"Two Sum","slug":"Two-Sum","date":"2017-05-02T20:58:00.000Z","updated":"2017-05-03T16:52:40.000Z","comments":true,"path":"2017/05/02/Two-Sum/","link":"","permalink":"https://minsooshin.github.io/2017/05/02/Two-Sum/","excerpt":"","text":"Source: leetcode 1. Two Sum Q. Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1]. Answer12345678910111213141516/** * @param {number[]} nums * @param {number} target * @return {number[]} */export default function twoSum (nums, target) { const seen = {} for (let i = 0; i < nums.length; i++) { const diff = target - nums[i] if (seen[diff] !== undefined) { return [seen[diff], i] } else { seen[nums[i]] = i } }}","categories":[{"name":"leetcode","slug":"leetcode","permalink":"https://minsooshin.github.io/categories/leetcode/"}],"tags":[{"name":"easy","slug":"easy","permalink":"https://minsooshin.github.io/tags/easy/"},{"name":"array","slug":"array","permalink":"https://minsooshin.github.io/tags/array/"},{"name":"hash table","slug":"hash-table","permalink":"https://minsooshin.github.io/tags/hash-table/"}]}]}