Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions 1-js/05-data-types/03-string/1-ucfirst/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,7 @@ let newStr = str[0].toUpperCase() + str.slice(1);

그런데 이렇게 코드를 작성하면 `str`이 비어있는 문자열인 경우 `str[0]`이 `undefined`가 되는 문제가 발생합니다. `undefined`는 `toUpperCase()`메서드를 지원하지 않으므로 에러가 발생하죠.

<<<<<<< HEAD
두 가지 방법을 사용해 이런 예외사항을 처리 할 수 있습니다.

1. `str.charAt(0)`은 `str`이 비어있는 문자열이더라도 항상 문자열을 반환하므로, 이 메서드를 사용합니다.
2. 빈 문자열인지를 확인하는 코드를 작성합니다.

두 번째 방법을 사용하여 작성한 답안은 아래와 같습니다.
=======
The easiest way out is to add a test for an empty string, like this:
>>>>>>> upstream/master
가장 간단한 해결 방법은 아래처럼 빈 문자열인지 확인하는 조건을 추가하는 것입니다.

```js run demo
function ucFirst(str) {
Expand Down
6 changes: 1 addition & 5 deletions 1-js/05-data-types/03-string/3-truncate/solution.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
새로 만든 문자열의 길이는 `maxlength`가 되어야 하므로, 생략 부호 `"…"`가 차지할 길이를 생각하여 함수를 만들어야 합니다.

<<<<<<< HEAD
생략 부호는 유니코드에 등록된 독립된 글자임에 유의하여 답안을 작성해야 합니다. 점 세 개가 아님에 유의하시기 바랍니다.
=======
Note that there is actually a single Unicode character for an ellipsis. That's not three dots.
>>>>>>> upstream/master
생략 부호는 유니코드에 등록된 하나의 문자입니다. 점 세 개가 아님에 유의하세요.

```js run demo
function truncate(str, maxlength) {
Expand Down
368 changes: 32 additions & 336 deletions 1-js/05-data-types/03-string/article.md

Large diffs are not rendered by default.

10 changes: 0 additions & 10 deletions 1-js/05-data-types/04-array/10-maximal-subarray/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,9 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
```

<<<<<<< HEAD
이렇게 구현하면 시간 복잡도가 [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation)이 됩니다. 이는 배열의 크기를 2배 늘리면 알고리즘은 4배나 더 오래 걸린다는 의미입니다.

크기가 큰 배열(1000, 10000 또는 그 이상의 요소를 가진 배열)에 위와 같은 알고리즘을 적용하면 매우 느릴 수 있습니다.
=======
The solution has a time complexity of [O(n<sup>2</sup>)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.

For big arrays (1000, 10000 or more items) such algorithms can lead to serious sluggishness.
>>>>>>> upstream/master

# 빠른 해답

Expand Down Expand Up @@ -97,8 +91,4 @@ alert( getMaxSubSum([-1, -2, -3]) ); // 0

이 알고리즘은 정확히 한번 배열을 순회하므로 시간 복잡도는 O(n)입니다.

<<<<<<< HEAD
알고리즘에 대한 상세한 정보는 [최대합 부분 배열 문제](http://en.wikipedia.org/wiki/Maximum_subarray_problem)에서 찾을 수 있습니다. 동작원리에 대해 확실히 이해가 되지 않았다면 위 예제의 알고리즘이 어떻게 동작하는지 찬찬히 살펴보세요. 글을 읽는 것보다 코드를 살펴보는게 훨씬 도움이 될 겁니다.
=======
You can find more detailed information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words.
>>>>>>> upstream/master
8 changes: 0 additions & 8 deletions 1-js/05-data-types/04-array/2-create-array/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,11 @@ importance: 5

배열과 관련된 다섯 가지 연산을 해봅시다.

<<<<<<< HEAD
1. 요소 "Jazz", "Blues"가 있는 `styles` 배열을 생성합니다.
2. "Rock-n-Roll"을 배열 끝에 추가합니다.
3. 배열 정 중앙에 있는 요소를 "Classics"로 바꿉니다. 가운데 요소를 찾는 코드는 요소가 홀수 개인 배열에서도 잘 작동해야 합니다.
4. 배열의 첫 번째 요소를 꺼내서 출력합니다.
5. "Rap"과 "Reggae"를 배열의 앞에 추가합니다.
=======
1. Create an array `styles` with items "Jazz" and "Blues".
2. Append "Rock-n-Roll" to the end.
3. Replace the value in the middle with "Classics". Your code for finding the middle value should work for any arrays with odd length.
4. Strip off the first value of the array and show it.
5. Prepend `Rap` and `Reggae` to the array.
>>>>>>> upstream/master

단계를 하나씩 거칠 때마다 배열 모습은 아래와 같이 변해야 합니다.

Expand Down
143 changes: 40 additions & 103 deletions 1-js/05-data-types/04-array/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,9 @@ In other words, `arr.at(i)`:

스택을 사용하면 가장 나중에 집어넣은 요소가 먼저 나옵니다. 이런 특징을 줄여서 후입선출(Last-In-First-Out, LIFO)이라고 부릅니다. 반면 큐를 사용하면 먼저 집어넣은 요소가 먼저 나오기 때문에 큐는 선입선출(First-In-First-Out, FIFO) 자료구조라고 부릅니다.

<<<<<<< HEAD
자바스크립트 배열을 사용하면 큐와 스택 둘 다를 만들 수 있습니다. 이 자료구조들은 배열의 처음이나 끝에 요소를 더하거나 빼는 데 사용되죠.

이렇게 처음이나 끝에 요소를 더하거나 빼주는 연산을 제공하는 자료구조를 컴퓨터 과학 분야에선 [데큐(deque, Double Ended Queue)](https://en.wikipedia.org/wiki/Double-ended_queue)라고 부릅니다.
=======
Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements, both to/from the beginning or the end.

In computer science, the data structure that allows this, is called [deque](https://en.wikipedia.org/wiki/Double-ended_queue).
>>>>>>> upstream/master

**아래는 배열 끝에 무언가를 해주는 메서드입니다.**

Expand Down Expand Up @@ -233,11 +227,7 @@ alert( fruits );

숫자형 키를 사용함으로써 배열은 객체 기본 기능 이외에도 순서가 있는 컬렉션을 제어하게 해주는 특별한 메서드를 제공합니다. `length`라는 프로퍼티도 제공하죠. 그렇지만 어쨌든 배열의 본질은 객체입니다.

<<<<<<< HEAD
이렇게 배열은 자바스크립트의 일곱 가지 원시 자료형에 해당하지 않고, 원시 자료형이 아닌 객체형에 속하기 때문에 객체처럼 동작합니다.
=======
Remember, there are only eight basic data types in JavaScript (see the [Data types](info:types) chapter for more info). Array is an object and thus behaves like an object.
>>>>>>> upstream/master
자바스크립트의 원시 자료형은 여덟 가지뿐입니다(자세한 내용은 [자료형](info:types) 챕터 참고). 배열은 원시 자료형이 아니라 객체에 속하므로 객체처럼 동작합니다.

예시를 하나 살펴봅시다. 배열은 객체와 마찬가지로 참조를 통해 복사됩니다.

Expand All @@ -253,11 +243,7 @@ arr.push("배"); // 참조를 이용해 배열을 수정합니다.
alert( fruits ); // 바나나,배 - 요소가 두 개가 되었습니다.
```

<<<<<<< HEAD
배열을 배열답게 만들어주는 것은 특수 내부 표현방식입니다. 자바스크립트 엔진은 아래쪽 그림에서처럼 배열의 요소를 인접한 메모리 공간에 차례로 저장해 연산 속도를 높입니다. 이 방법 이외에도 배열 관련 연산을 더 빠르게 해주는 최적화 기법은 다양합니다.
=======
...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast.
>>>>>>> upstream/master
배열을 배열답게 만들어주는 것은 특수 내부 표현 방식입니다. 자바스크립트 엔진은 아래쪽 그림에서처럼 배열의 요소를 인접한 메모리 공간에 차례로 저장해 연산 속도를 높입니다. 이 방법 이외에도 배열 관련 연산을 더 빠르게 해주는 최적화 기법은 다양합니다.

그런데 개발자가 배열을 '순서가 있는 자료의 컬렉션'처럼 다루지 않고 일반 객체처럼 다루면 이런 기법들이 제대로 동작하지 않습니다.

Expand Down Expand Up @@ -295,11 +281,7 @@ fruits.age = 25; // 임의의 이름을 사용해 프로퍼티를 만듭니다.
fruits.shift(); // 배열 맨 앞의 요소를 빼줍니다.
```

<<<<<<< HEAD
`shift` 메서드를 호출한 것과 동일한 효과를 보려면 인덱스가 `0`인 요소를 제거하는 것만으론 충분하지 않습니다. 제거 대상이 아닌 나머지 요소들의 인덱스를 수정해 줘야 하죠.
=======
It's not enough to take and remove the element with the index `0`. Other elements need to be renumbered as well.
>>>>>>> upstream/master

`shift` 연산은 아래 3가지 동작을 모두 수행해야 이뤄집니다.

Expand Down Expand Up @@ -417,19 +399,11 @@ alert( arr[3] ); // undefined: 삭제된 기존 요소들이 복구되지 않습
let arr = *!*new Array*/!*("사과", "배", "기타");
```

<<<<<<< HEAD
대괄호 `[]`를 사용하면 더 짧은 문법으로 배열을 만들 수 있기 때문에 `new Array()`는 잘 사용되지 않는 편입니다. `new Array()`엔 다루기 까다로운 기능도 있어서 더욱더 그렇습니다.
=======
It's rarely used, because square brackets `[]` are shorter. Also, there's a tricky feature with it.
>>>>>>> upstream/master
대괄호 `[]`를 사용하면 더 짧은 문법으로 배열을 만들 수 있기 때문에 `new Array`는 잘 사용되지 않는 편입니다. `new Array`엔 다루기 까다로운 기능도 있어서 더욱더 그렇습니다.

숫자형 인수 하나를 넣어서 `new Array`를 호출하면 배열이 만들어지는데, 이 배열엔 *요소가 없는 반면 길이는 인수와 같아*집니다.

<<<<<<< HEAD
예시를 통해 `new Array()`의 이런 특징이 어떻게 실수를 유발할 수 있는지 알아봅시다.
=======
Let's see how one can shoot themselves in the foot:
>>>>>>> upstream/master
예시를 통해 `new Array`의 이런 특징이 어떻게 실수를 유발할 수 있는지 알아봅시다.

```js run
let arr = new Array(2); // 이렇게 하면 배열 [2]가 만들어질까요?
Expand All @@ -439,13 +413,7 @@ alert( arr[0] ); // undefined가 출력됩니다. 요소가 하나도 없는 배
alert( arr.length ); // 길이는 2입니다.
```

<<<<<<< HEAD
위 예시에서 확인해 본 것처럼 `new Array(number)`를 이용해 만든 배열의 요소는 모두 `undefined` 입니다.

이런 뜻밖의 상황을 마주치지 않기 위해 `new Array`의 기능을 잘 알지 않는 한 대부분의 개발자가 대괄호를 써서 배열을 만듭니다.
=======
To avoid such surprises, we usually use square brackets, unless we really know what we're doing.
>>>>>>> upstream/master
위 예시에서 확인해 본 것처럼 `new Array(number)`를 이용해 만든 배열의 요소는 모두 `undefined` 입니다. 이런 뜻밖의 상황을 마주치지 않기 위해 `new Array`의 기능을 잘 알지 않는 한 대부분의 개발자가 대괄호를 써서 배열을 만듭니다.

## 다차원 배열

Expand All @@ -458,11 +426,7 @@ let matrix = [
[7, 8, 9]
];

<<<<<<< HEAD
alert( matrix[1][1] ); // 5, 중심에 있는 요소
=======
alert( matrix[0][1] ); // 2, the second value of the first inner array
>>>>>>> upstream/master
alert( matrix[0][1] ); // 2, 첫 번째 내부 배열의 두번째 값
```

## toString
Expand Down Expand Up @@ -497,100 +461,77 @@ alert( "1" + 1 ); // "11"
alert( "1,2" + 1 ); // "1,21"
```

<<<<<<< HEAD
## 요약
=======
## Don't compare arrays with ==

Arrays in JavaScript, unlike some other programming languages, shouldn't be compared with operator `==`.
## ==로 배열을 비교하지 마세요

This operator has no special treatment for arrays, it works with them as with any objects.
자바스크립트에서 배열은 다른 몇몇 프로그래밍 언어와 달리 ==연산자로 비교하면 안 됩니다.

Let's recall the rules:
==연산자는 배열을 특별하게 취급하지 않습니다. 배열도 일반 객체처럼 처리됩니다.

- Two objects are equal `==` only if they're references to the same object.
- If one of the arguments of `==` is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter <info:object-toprimitive>.
- ...With an exception of `null` and `undefined` that equal `==` each other and nothing else.
규칙을 다시 떠올려 봅시다.
- 두 객체는 동일한 객체를 참조할 때만 `==` 비교 결과가 `true`입니다.
- `==`의 피연산자 중 하나가 객체이고 다른 하나가 primitive 자료형이면, <info:object-toprimitive> 챕터에서 설명한 것처럼 객체가 원시값으로 변환됩니다.
- 단, `null`과 `undefined`는 예외로 서로끼리만 `==` 비교 시 같고, 다른 값과는 같지 않습니다.

The strict comparison `===` is even simpler, as it doesn't convert types.
엄격한 비교 연산자 `===`는 더 단순합니다. 타입 변환을 수행하지 않기 때문입니다.

So, if we compare arrays with `==`, they are never the same, unless we compare two variables that reference exactly the same array.
따라서 배열을 `==`로 비교하면, 정확히 같은 배열을 참조하는 두 변수를 비교하는 경우가 아니라면 항상 서로 다르다고 판단됩니다.

For example:
예시:
```js run
alert( [] == [] ); // false
alert( [0] == [0] ); // false
alert( [] == [] ); //false
alert( [0] == [0] ); //false
```

These arrays are technically different objects. So they aren't equal. The `==` operator doesn't do item-by-item comparison.
위 배열들은 엄밀히 말하면 서로 다른 객체입니다. 따라서 같지 않습니다. `==` 연산자는 배열 요소를 하나씩 비교하지 않습니다.

Comparison with primitives may give seemingly strange results as well:
원시값과 비교할 때도 이상해 보이는 결과가 나올 수 있습니다.

```js run
alert( 0 == [] ); // true

alert('0' == [] ); // false
```

Here, in both cases, we compare a primitive with an array object. So the array `[]` gets converted to primitive for the purpose of comparison and becomes an empty string `''`.
여기서는 두 경우 모두 원시값과 배열 객체를 비교하고 있습니다. 따라서 비교를 위해 배열 `[]`가 원시값으로 변환되며, 빈 문자열 ``이 됩니다.

Then the comparison process goes on with the primitives, as described in the chapter <info:type-conversions>:
그 후 비교는 <info:type-conversions> 챕터에서 설명한 원시값 비교 규칙에 따라 진행됩니다.

```js run
// after [] was converted to ''
alert( 0 == '' ); // true, as '' becomes converted to number 0
// []가 ''로 변환된 이후
alert( 0 == '' ); // true, ''가 숫자 0으로 변환됨

alert('0' == '' ); // false, no type conversion, different strings
alert('0' == '' ); // false, 타입 변환이 일어나지 않으며 서로 다른 문자열임
```

So, how to compare arrays?
그렇다면 배열은 어떻게 비교해야 할까요?

That's simple: don't use the `==` operator. Instead, compare them item-by-item in a loop or using iteration methods explained in the next chapter.
간단합니다. `==` 연산자를 사용하지 마세요. 대신 반복문이나 다음 챕터에서 설명할 순회 메서드를 사용해 요소를 하나씩 비교하면 됩니다.

## Summary
>>>>>>> upstream/master
## 요약

배열은 특수한 형태의 객체로, 순서가 있는 자료를 저장하고 관리하는 용도에 최적화된 자료구조입니다.

<<<<<<< HEAD
- 선언 방법:

```js
// 대괄호 (가장 많이 쓰이는 방법임)
let arr = [item1, item2...];

// new Array (잘 쓰이지 않음)
let arr = new Array(item1, item2...);
```

`new Array(number)`을 호출하면 길이가 `number`인 배열이 만들어지는데, 이 때 요소는 비어있습니다.
=======
The declaration:
선언 방법:

```js
// square brackets (usual)
// 대괄호 (가장 많이 쓰이는 방법임)
let arr = [item1, item2...];

// new Array (exceptionally rare)
// new Array (잘 쓰이지 않음)
let arr = new Array(item1, item2...);
```

The call to `new Array(number)` creates an array with the given length, but without elements.
>>>>>>> upstream/master
`new Array(number)`을 호출하면 길이가 `number`인 배열이 만들어지는데, 이때 요소는 비어 있습니다.

- `length` 프로퍼티는 배열의 길이를 나타내줍니다. 정확히는 숫자형 인덱스 중 가장 큰 값에 1을 더한 값입니다. 배열 메서드는 `length` 프로퍼티를 자동으로 조정해줍니다.
- `length` 값을 수동으로 줄이면 배열 끝이 잘립니다.

<<<<<<< HEAD
다음 연산을 사용하면 배열을 데큐처럼 사용할 수 있습니다.
=======
Getting the elements:

- we can get element by its index, like `arr[0]`
- also we can use `at(i)` method that allows negative indexes. For negative values of `i`, it steps back from the end of the array. If `i >= 0`, it works same as `arr[i]`.
요소에 접근하는 방법:

We can use an array as a deque with the following operations:
>>>>>>> upstream/master
- `arr[0]`처럼 인덱스를 사용해 요소를 가져올 수 있습니다.
- 음수 인덱스를 지원하는 `at(i)` 메서드도 사용할 수 있습니다. `i`가 음수이면 배열 끝에서부터 거슬러 올라가며 요소를 찾습니다. `i>=0`인 경우에는 `arr[i]`와 동일하게 동작합니다.

다음 연산을 사용하면 배열을 데큐처럼 사용할 수 있습니다.

- `push(...items)` -- `items`를 배열 끝에 더해줍니다.
- `pop()` -- 배열 끝 요소를 제거하고, 제거한 요소를 반환합니다.
Expand All @@ -602,12 +543,8 @@ We can use an array as a deque with the following operations:
- `for (let item of arr)` -- 배열 요소에만 사용되는 모던한 문법입니다.
- `for (let i in arr)` -- 배열엔 절대 사용하지 마세요.

<<<<<<< HEAD
<info:array-methods> 챕터에선 배열에 요소를 더하거나 빼기, 원하는 요소를 추출하기, 배열 정렬하기 등과 관련된 다양한 메서드를 학습할 예정입니다.
=======
To compare arrays, don't use the `==` operator (as well as `>`, `<` and others), as they have no special treatment for arrays. They handle them as any objects, and it's not what we usually want.
배열을 비교할 때는 `==` 연산자(`>`,`<` 등의 비교 연산자도 마찬가지)를 사용하지 마세요. 이러한 연산자들은 배열을 특별하게 처리하지 않고 일반 객체처럼 다루기 때문에, 우리가 기대하는 방식으로 동작하지 않습니다.

Instead you can use `for..of` loop to compare arrays item-by-item.
대신 `for..of` 반복문을 사용해 배열 요소를 하나씩 비교할 수 있습니다.

We will continue with arrays and study more methods to add, remove, extract elements and sort arrays in the next chapter <info:array-methods>.
>>>>>>> upstream/master
<info:array-methods> 챕터에선 배열에 요소를 더하거나 빼기, 원하는 요소를 추출하기, 배열 정렬하기 등과 관련된 다양한 메서드를 학습할 예정입니다.
6 changes: 1 addition & 5 deletions 1-js/05-data-types/05-array-methods/2-filter-range/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@

# 특정 범위에 속하는 요소 찾기

<<<<<<< HEAD
배열 `arr`의 요소 중 `a`이상 `b` 이하 범위에 속하는 요소만 골라 새로운 배열에 집어넣고, 해당 요소를 출력해주는 함수 `filterRange(arr, a, b)`를 작성해봅시다.
=======
Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements with values higher or equal to `a` and lower or equal to `b` and return a result as an array.
>>>>>>> upstream/master
배열 `arr`의 요소 중 `a` 이상 `b` 이하 범위에 속하는 요소만 골라 새로운 배열에 집어넣고, 해당 요소를 출력해 주는 함수 `filterRange(arr, a, b)`를 작성해 봅시다.

새로 작성하는 함수는 기존 배열 `arr`을 변경하면 안 되고, 반환되는 함수는 새로운 배열이어야 합니다.

Expand Down
Loading