Code Convention Tooling for Better Collaboratation

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.

Read More

Share Comments

React Fiber: 사실에 입각한 루머 정리

최근 자바스크립트 프레임워크들이 당신이 주로 다루는 것이라면, 아마도 최근들어 사람들이 React Fiber 에 대해서 이야기 하는 것을 들어봤을 것 입니다.

React 의 “다음 버전”을 학수 고대하고 그것을 적용하여 당신의 앱들을 모던 앱의 가볍고 빠르게 변화시키고 싶을지도 모릅니다. 또 한편으로 좌절감이 느껴질 정도로 빠른 자바스크립트 프레임워크들의 발생, 진화, 소멸의 속도를 보면, 이 Fiber 도 당신에게 극심한 혼돈을 야기할 수도 있습니다.

자, 심호흡 한 번 하시고 이제 시작하겠습니다. 이 글의 목적은 당신을 조금이라도 안도하게 하고 Fiber 에 관한 잘못된 상식들을 바로 잡고자 함입니다.

Read More

Share Comments

Find All Duplicates in an Array

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]

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @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
}

Share Comments

Convert Sorted Array to Binary Search Tree

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.

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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)
}

Share Comments

Asynchronous JavaScript with async/await

1. Write an Asynchronous Function with async/await

Here, we have short function that talks with a github API.

1
2
3
4
5
6
7
8
9
10
11
12
13
const 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.

This is the result of execution

Read More

Share Comments

Search Insert Position

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

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @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
}

Share Comments

Contains Duplicate

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.

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @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
}

Share Comments

Reverse String

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 pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @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 concatenation

1
2
3
4
5
6
7
8
9
10
11
/**
* @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
}

Share Comments

Single Number

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 memory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @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 memory

1
2
3
4
5
6
7
/**
* @param {number[]} nums
* @return {number}
*/
export default function singleNumber (nums) {
return nums.reduce((curr, prev) => curr ^ prev)
}

Share Comments

Two Sum

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].

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @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
}
}
}

Share Comments