chore(i18n,learn): processed translations (#44851)
This commit is contained in:
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b67
|
||||
title: push の代わりに concat を使用して要素を配列の末尾に追加する
|
||||
challengeType: 1
|
||||
forumTopicId: 301226
|
||||
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
関数型プログラミングで重要なのは、ミューテーションを起こさない関数を作成して使用することです。
|
||||
|
||||
前回のチャレンジでは、元の配列をミューテートさせずに配列を新しい配列に結合する方法として、`concat` メソッドを紹介しました。 `concat` を `push` メソッドと比較してみましょう。 `push` は、呼び出された同じ配列の末尾にアイテムを追加し、その配列をミューテートさせます。 例を示します。
|
||||
|
||||
```js
|
||||
const arr = [1, 2, 3];
|
||||
arr.push([4, 5, 6]);
|
||||
```
|
||||
|
||||
`arr` の変更後の値は `[1, 2, 3, [4, 5, 6]]` となりますが、これは関数型プログラミングの方法ではありません。
|
||||
|
||||
`concat` では、ミューテーションの副作用を起こさずに、配列の末尾に新しいアイテムを追加できます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`nonMutatingPush` 関数を変更し、`push` の代わりに `concat` を使用して `newItem` を `original` の末尾に追加するようにしてください。 この関数は配列を返す必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `concat` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
コードで `push` メソッドを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?push/g));
|
||||
```
|
||||
|
||||
`first` 配列を変更しないようにする必要があります。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
`second` 配列を変更しないようにする必要があります。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingPush([1, 2, 3], [4, 5])` は `[1, 2, 3, 4, 5]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
|
||||
JSON.stringify([1, 2, 3, 4, 5])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
// Only change code below this line
|
||||
return original.push(newItem);
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
const first = [1, 2, 3];
|
||||
const second = [4, 5];
|
||||
nonMutatingPush(first, second);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
return original.concat(newItem);
|
||||
}
|
||||
const first = [1, 2, 3];
|
||||
const second = [4, 5];
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6d
|
||||
title: 関数型プログラミングを適用して文字列を URL スラッグに変換する
|
||||
challengeType: 1
|
||||
forumTopicId: 301227
|
||||
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
最後のいくつかのチャレンジでは、関数型プログラミングの原則に従う数多くの便利な配列メソッドや文字列メソッドを取り上げまました。 また、`reduce` についても学びました。これは強力なメソッドで、これを使用して問題をより簡単な形に減らすことができます。 平均の計算からソートに至るまで、どのような配列演算にも適用することができます。 `map` と `filter` が `reduce` の特殊なケースであることも覚えておきましょう。
|
||||
|
||||
ここまで学んだことを駆使して、実際の問題を解決してみましょう。
|
||||
|
||||
多くのコンテンツ管理サイト (CMS) では、ブックマークを簡単に付けられるように、投稿のタイトルが URL の一部に追加されています。 たとえば、Medium で `Stop Using Reduce` というタイトルの記事を書いた場合、その URL にはタイトル文字列が何らかの形で含まれる可能性が高くなります (`.../stop-using-reduce`)。 すでに freeCodeCamp サイトで気づいている方もいらっしゃるかもしれません。
|
||||
|
||||
# --instructions--
|
||||
|
||||
文字列 `title` を変換して、ハイフンつなぎの URL を返す、`urlSlug` 関数を記述してください。 このセクションで取り上げたすべてのメソッドを使用できますが、`replace` は使用しないでください。 要件は次のとおりです。
|
||||
|
||||
入力は、スペースとタイトルケースの単語を含む文字列
|
||||
|
||||
出力は、単語間のスペースをハイフン (`-`) に置き換えた文字列
|
||||
|
||||
出力はすべて小文字
|
||||
|
||||
出力にはスペースを含めない
|
||||
|
||||
# --hints--
|
||||
|
||||
このチャレンジに `replace` メソッドを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`urlSlug("Winter Is Coming")` は文字列 `winter-is-coming` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug(" Winter Is Coming")` は文字列 `winter-is-coming` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` は文字列 `a-mind-needs-books-like-a-sword-needs-a-whetstone` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone') ===
|
||||
'a-mind-needs-books-like-a-sword-needs-a-whetstone'
|
||||
);
|
||||
```
|
||||
|
||||
`urlSlug("Hold The Door")` は文字列 `hold-the-door` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(urlSlug('Hold The Door') === 'hold-the-door');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
function urlSlug(title) {
|
||||
|
||||
|
||||
}
|
||||
// Only change code above this line
|
||||
urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function urlSlug(title) {
|
||||
return title.trim().split(/\s+/).join("-").toLowerCase();
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5e
|
||||
title: 関数型プログラミングを使用してミューテーションや副作用を回避する
|
||||
challengeType: 1
|
||||
forumTopicId: 301228
|
||||
dashedName: avoid-mutations-and-side-effects-using-functional-programming
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
まだ気づいていない方もいるかもしれませんが、 前回のチャレンジには `tabClose()` 関数の `splice` 呼び出しに問題がありました。 残念ながら、`splice` は呼び出しの対象となる元の配列を変更します。そのため、2 つ目の呼び出しでは変更後の配列が使用され、予期しない結果をもたらしました。
|
||||
|
||||
これははるかに大きなパターンの小さな一例にすぎません。変数、配列、またはオブジェクトに対して関数を呼び出すと、関数によってオブジェクトの変数などが変更されます。
|
||||
|
||||
関数型プログラミングの基本原則の一つは、何も変更を加えないことです。 変更はバグにつながります。 関数の引数やグローバル変数なども含めて「自分の関数は何も変更を加えない」という認識を持ちながらバグを防ぐ方が簡単です。
|
||||
|
||||
前の例では複雑な操作はありませんでしたが、`splice` メソッドによって元の配列が変更され、バグが発生しました。
|
||||
|
||||
すでに説明しましたが、関数型プログラミングでは、何らかの変更が生じることを<dfn>ミューテーション</dfn>と呼び、その結果のことを<dfn>副作用</dfn>と呼びます。 関数は、理想的には<dfn>純粋な関数</dfn>、つまり、副作用を起こさない関数でなければなりません。
|
||||
|
||||
この原則を実践して、コード内の変数やオブジェクトを変更しないようにしましょう。
|
||||
|
||||
# --instructions--
|
||||
|
||||
関数 `incrementer` のコードを記述して、グローバル変数 `fixedValue` の値を 1 増やして返してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
関数 `incrementer` は `fixedValue` の値 (`4`) を変更してはいけません。
|
||||
|
||||
```js
|
||||
incrementer();
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
`incrementer` 関数は、`fixedValue` 値よりも 1 大きい値を返す必要があります。
|
||||
|
||||
```js
|
||||
const __newValue = incrementer();
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
`incrementer` 関数は、グローバル変数 `fixedValue` の値に基づいて値を返す必要があります。
|
||||
|
||||
```js
|
||||
(function () {
|
||||
fixedValue = 10;
|
||||
const newValue = incrementer();
|
||||
assert(fixedValue === 10 && newValue === 11);
|
||||
fixedValue = 4;
|
||||
})();
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
let fixedValue = 4;
|
||||
|
||||
function incrementer() {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let fixedValue = 4
|
||||
|
||||
function incrementer() {
|
||||
return fixedValue + 1
|
||||
}
|
||||
```
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6c
|
||||
title: join メソッドを使用して配列を文字列に結合する
|
||||
challengeType: 1
|
||||
forumTopicId: 18221
|
||||
dashedName: combine-an-array-into-a-string-using-the-join-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`join` メソッドは、配列の要素を結合して文字列を作成するのに使用します。 このメソッドは、文字列内の配列要素の分割に使用される区切り文字の引数を取ります。
|
||||
|
||||
例を示します。
|
||||
|
||||
```js
|
||||
const arr = ["Hello", "World"];
|
||||
const str = arr.join(" ");
|
||||
```
|
||||
|
||||
`str` の値は文字列 `Hello World` になります。
|
||||
# --instructions--
|
||||
|
||||
`sentensify` 関数の中で、(特に) `join` メソッドを使用して、文字列 `str` 内の単語から文章を作成してください。 この関数は文字列を返す必要があります。 たとえば、`I-like-Star-Wars` は `I like Star Wars` に変換されます。 このチャレンジでは `replace` メソッドを使用しないでください。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードでは `join` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.join/g));
|
||||
```
|
||||
|
||||
`replace` メソッドを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` は文字列を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` は文字列 `May the force be with you` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
|
||||
```
|
||||
|
||||
`sentensify("The.force.is.strong.with.this.one")` は文字列 `The force is strong with this one` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
sentensify('The.force.is.strong.with.this.one') ===
|
||||
'The force is strong with this one'
|
||||
);
|
||||
```
|
||||
|
||||
`sentensify("There,has,been,an,awakening")` は文字列 `There has been an awakening` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
sentensify('There,has,been,an,awakening') === 'There has been an awakening'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
sentensify("May-the-force-be-with-you");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
return str.split(/\W/).join(' ');
|
||||
}
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b66
|
||||
title: concat メソッドを使用して 2 つの配列を連結する
|
||||
challengeType: 1
|
||||
forumTopicId: 301229
|
||||
dashedName: combine-two-arrays-using-the-concat-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
複数のアイテムを最初から最後まで結合することを<dfn>連結 (Concatenation)</dfn> と呼びます。 JavaScript で提供されている `concat` メソッドは、文字列でも配列でも同じ動作をします。 配列の場合は、一方の配列でメソッドを呼び出してから、もう一方の配列を `concat` の引数として与えると、その配列が最初の配列の末尾に追加されます。 このメソッドは新しい配列を返し、元の配列のいずれもミューテートさせません。 例を示します。
|
||||
|
||||
```js
|
||||
[1, 2, 3].concat([4, 5, 6]);
|
||||
```
|
||||
|
||||
返される配列は `[1, 2, 3, 4, 5, 6]` となります。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`nonMutatingConcat` 関数で `concat` メソッドを使用して、`original` の末尾に `attach` を連結してください。 この関数は連結した配列を返す必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードでは `concat` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
`first` 配列は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
`second` 配列は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingConcat([1, 2, 3], [4, 5])` は `[1, 2, 3, 4, 5]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) ===
|
||||
JSON.stringify([1, 2, 3, 4, 5])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
const first = [1, 2, 3];
|
||||
const second = [4, 5];
|
||||
nonMutatingConcat(first, second);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
return original.concat(attach);
|
||||
}
|
||||
const first = [1, 2, 3];
|
||||
const second = [4, 5];
|
||||
```
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b62
|
||||
title: プロトタイプに map を実装する
|
||||
challengeType: 1
|
||||
forumTopicId: 301230
|
||||
dashedName: implement-map-on-a-prototype
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
前に説明した `Array.prototype.map()` (または単純に `map()`) の適用からわかるように、`map` メソッドは、呼び出された配列と同じ長さの配列を返します。 また、コールバック関数で操作しない限り、元の配列も変更しません。
|
||||
|
||||
言い換えれば、`map` は純粋な関数であり、その出力は入力にのみ依存します。 さらに、引数として別の関数を取ります。
|
||||
|
||||
`map` メソッドについては、独自のバージョンを実装することで多くのことを学べるかもしれません。 `for` ループまたは `Array.prototype.forEach()` を使用することをお勧めします。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`Array.prototype.map()` とまったく同じように動作する、独自の `Array.prototype.myMap()`を記述してください。 組み込みの `map` メソッドを使用しないでください。 `myMap` メソッドで `Array` インスタンスにアクセスするには `this` を使用します。
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` は `[46, 130, 196, 10]` と等しくなければなりません。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
|
||||
```
|
||||
|
||||
コードでは `map` メソッドを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?map/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback) {
|
||||
const newArray = [];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
const new_s = s.myMap(function(item) {
|
||||
return item * 2;
|
||||
});
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback) {
|
||||
const newArray = [];
|
||||
for (const elem of this) {
|
||||
newArray.push(callback(elem));
|
||||
}
|
||||
return newArray;
|
||||
};
|
||||
|
||||
const new_s = s.myMap(function(item) {
|
||||
return item * 2;
|
||||
});
|
||||
```
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b64
|
||||
title: プロトタイプに filter メソッドを実装する
|
||||
challengeType: 1
|
||||
forumTopicId: 301231
|
||||
dashedName: implement-the-filter-method-on-a-prototype
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`filter` メソッドについては、独自のバージョンを実装することで多くのことを学べるかもしれません。 `for` ループまたは `Array.prototype.forEach()` を使用することをお勧めします。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`Array.prototype.filter()` とまったく同じように動作する、独自の `Array.prototype.myFilter()`を記述してください。 組み込みの `filter` メソッドを使用しないでください。 `myFilter` メソッドで `Array` インスタンスにアクセスするには `this` を使用します。
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` は `[23, 65, 5]` と等しくなければなりません。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
|
||||
```
|
||||
|
||||
`filter` メソッドを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?filter/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback) {
|
||||
// Only change code below this line
|
||||
const newArray = [];
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
const new_s = s.myFilter(function(item) {
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback) {
|
||||
const newArray = [];
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
if (callback(this[i])) newArray.push(this[i]);
|
||||
}
|
||||
return newArray;
|
||||
};
|
||||
|
||||
const new_s = s.myFilter(function(item) {
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b70
|
||||
title: カリー化と部分適用について
|
||||
challengeType: 1
|
||||
forumTopicId: 301232
|
||||
dashedName: introduction-to-currying-and-partial-application
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
関数が必要とする引数の数のことを、関数の<dfn>アリティ</dfn>と呼びます。 アリティが N の 1 個の関数を、アリティが 1 の N 個の関数に変換することを、関数の<dfn>カリー化</dfn>と呼びます。
|
||||
|
||||
言い換えれば、1 つの引数を取るように関数を再構築して、次の引数を取る別の関数を返し、その別の関数でも同様の操作をします。
|
||||
|
||||
例を示します。
|
||||
|
||||
```js
|
||||
function unCurried(x, y) {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
function curried(x) {
|
||||
return function(y) {
|
||||
return x + y;
|
||||
}
|
||||
}
|
||||
|
||||
const curried = x => y => x + y
|
||||
|
||||
curried(1)(2)
|
||||
```
|
||||
|
||||
`curried(1)(2)` は `3` を返します。
|
||||
|
||||
これはプログラムにおいて、関数に対して一度にすべての引数を与えることができない場合に便利です。 それぞれの関数呼び出しを変数に保存しておき、返された関数参照を変数に保持して、次の引数が利用可能になった時点でその引数を受け取るようにすることができます。 前の例のカリー化した関数の使用例を次に示します。
|
||||
|
||||
```js
|
||||
const funcForY = curried(1);
|
||||
console.log(funcForY(2)); // 3
|
||||
```
|
||||
|
||||
同様に、一度にいくつかの引数を 1 つの関数に適用し、より多くの引数を適用する別の関数を返すことを、<dfn>部分適用</dfn>と呼びます。 例を示します。
|
||||
|
||||
```js
|
||||
function impartial(x, y, z) {
|
||||
return x + y + z;
|
||||
}
|
||||
|
||||
const partialFn = impartial.bind(this, 1, 2);
|
||||
partialFn(10); // 13
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
カリー化を使用してパラメーター `x`、`y`、`z` を加算するように、`add` 関数の本体を記述してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
`add(10)(20)(30)` は `60` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(add(10)(20)(30) === 60);
|
||||
```
|
||||
|
||||
`add(1)(2)(3)` は `6` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(add(1)(2)(3) === 6);
|
||||
```
|
||||
|
||||
`add(11)(22)(33)` は `66` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(add(11)(22)(33) === 66);
|
||||
```
|
||||
|
||||
コードの最後には、`x + y + z` を返すステートメントを含める必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function add(x) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
add(10)(20)(30);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const add = x => y => z => x + y + z
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 587d7b8d367417b2b2512b5b
|
||||
title: 関数型プログラミングについて学習する
|
||||
challengeType: 1
|
||||
forumTopicId: 301233
|
||||
dashedName: learn-about-functional-programming
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
関数型プログラミングはプログラミングのスタイルの一つで、ソリューションが単純で独立した関数であり、関数スコープ外の副作用がありません: `INPUT -> PROCESS -> OUTPUT`
|
||||
|
||||
関数型プログラミングでは次のような関数を目指します。
|
||||
|
||||
1) 独立した関数 - プログラムの状態 (変更される可能性があるグローバル変数を含む) にまったく依存しない
|
||||
|
||||
2) 純粋な関数 - 同じ入力は常に同じ出力を与える
|
||||
|
||||
3) 限られた副作用を持つ関数 - 関数外のプログラムの状態に対する任意の変更 (ミューテーション) は慎重に制御される
|
||||
|
||||
# --instructions--
|
||||
|
||||
freeCodeCamp のメンバーはたまたま紅茶が大好きです。
|
||||
|
||||
コードエディターでは、`prepareTea` および `getTea` 関数がすでに定義されています。 `getTea` 関数を呼び出して、チームの紅茶 40 杯分をもらい、`tea4TeamFCC` 変数に格納してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
`tea4TeamFCC` 変数には、チームの 40 杯分の紅茶を保持する必要があります。
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC.length === 40);
|
||||
```
|
||||
|
||||
`tea4TeamFCC` 変数には、緑茶を数杯分保持する必要があります。
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Function that returns a string representing a cup of green tea
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
/*
|
||||
Given a function (representing the tea type) and number of cups needed, the
|
||||
following function returns an array of strings (each representing a cup of
|
||||
a specific type of tea).
|
||||
*/
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
const tea4TeamFCC = null;
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
const tea4TeamFCC = getTea(40);
|
||||
```
|
@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5f
|
||||
title: 関数内の外部依存を回避するために引数を渡す
|
||||
challengeType: 1
|
||||
forumTopicId: 301234
|
||||
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
前回のチャレンジで、関数型プログラミングの原則に一歩近づきましたが、まだ何かが欠けています。
|
||||
|
||||
グローバル変数の値は変更しませんでしたが、関数 `incrementer` はグローバル変数 `fixedValue` がなければ動作しませんでした。
|
||||
|
||||
関数型プログラミングのもう一つの原則は、常に依存関係を明示的に宣言することです。 つまり、関数が変数やオブジェクトの存在に依存している場合は、その変数やオブジェクトを引数として関数に直接渡します。
|
||||
|
||||
この原則からはいくつかの良い結果がもたらされます。 この関数はテストが簡単になります。どのような入力を受け取るかが正確にわかり、プログラムの他の部分には依存しません。
|
||||
|
||||
このため、新しいコードを変更、削除、または追加する際に、安心感が強まります。 何が変更できて何が変更できないかがわかり、潜在的な罠がどこに潜んでいるかがわかります。
|
||||
|
||||
さらに、関数はコードのどの部分で実行されても、同じ一連の入力に対して常に同じ出力を生成します。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`incrementer` 関数を更新して、依存関係を明確に宣言しましょう。
|
||||
|
||||
引数を取り、値を 1 増やした後に結果を返すように、`incrementer` 関数を記述してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
関数 `incrementer` は `fixedValue` の値 (`4`) を変更してはいけません。
|
||||
|
||||
```js
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
`incrementer` 関数は引数を取る必要があります。
|
||||
|
||||
```js
|
||||
assert(incrementer.length === 1);
|
||||
```
|
||||
|
||||
`incrementer` 関数は、`fixedValue` 値よりも 1 大きい値を返す必要があります。
|
||||
|
||||
```js
|
||||
const __newValue = incrementer(fixedValue);
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
let fixedValue = 4;
|
||||
|
||||
// Only change code below this line
|
||||
function incrementer() {
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let fixedValue = 4;
|
||||
|
||||
function incrementer(fixedValue) {
|
||||
return fixedValue + 1;
|
||||
}
|
||||
```
|
@ -0,0 +1,132 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b60
|
||||
title: 関数の影響を受けないようにグローバル変数をリファクタリングする
|
||||
challengeType: 1
|
||||
forumTopicId: 301235
|
||||
dashedName: refactor-global-variables-out-of-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
ここまで、関数型プログラミングの 2 つの異なる原則について説明しました。
|
||||
|
||||
1) 変数やオブジェクトを変更しないこと - 新しい変数やオブジェクトを作成し、必要に応じて関数からそれらを返します。 ヒント: `const newArr = arrVar` のようなものを使用した場合、`arrVar` が配列であれば、コピーを作成するのではなく、既存の変数への参照を作成するだけです。 そのため、`newArr` の値を変更すると、`arrVar` の値が変更されます。
|
||||
|
||||
2) 関数パラメーターを宣言すること - 関数内の計算はどれも、関数に渡された引数にのみ依存し、グローバルのオブジェクトや変数には依存しません。
|
||||
|
||||
ある数に 1 を加えることはあまり面白くありませんが、配列や複雑なオブジェクトを扱う場合には、上記の原則を適用できます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
グローバル配列 `bookList` がどちらの関数内でも変更されないようにコードを書き換えてください。 `add` 関数は、与えられた `bookName` を、渡された配列の末尾に追加し、新しい配列 (リスト) を返す必要があります。 `remove` 関数は、与えられた `bookName` を、渡された配列から削除する必要があります。
|
||||
|
||||
**注:** どちらの関数も配列を返す必要があり、新しいパラメーターを `bookName` パラメーターの前に追加する必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
`bookList` は、変更されず、`["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]` と等しくなる必要があります。
|
||||
|
||||
```js
|
||||
add(bookList, "Test");
|
||||
assert(
|
||||
JSON.stringify(bookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'On The Electrodynamics of Moving Bodies',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`add(bookList, "A Brief History of Time")` は `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(add(bookList, "A Brief History of Time")) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'On The Electrodynamics of Moving Bodies',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae',
|
||||
'A Brief History of Time'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`remove(bookList, "On The Electrodynamics of Moving Bodies")` は `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(remove(bookList, 'On The Electrodynamics of Moving Bodies')) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`remove(add(bookList, "A Brief History of Time"), "On The Electrodynamics of Moving Bodies");` の結果は `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]` と等しくなる必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies')) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae',
|
||||
'A Brief History of Time'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
// Change code below this line
|
||||
function add(bookName) {
|
||||
|
||||
bookList.push(bookName);
|
||||
return bookList;
|
||||
|
||||
// Change code above this line
|
||||
}
|
||||
|
||||
// Change code below this line
|
||||
function remove(bookName) {
|
||||
const book_index = bookList.indexOf(bookName);
|
||||
if (book_index >= 0) {
|
||||
|
||||
bookList.splice(book_index, 1);
|
||||
return bookList;
|
||||
|
||||
// Change code above this line
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
function add(bookList, bookName) {
|
||||
return [...bookList, bookName];
|
||||
}
|
||||
|
||||
function remove(bookList, bookName) {
|
||||
const bookListCopy = [...bookList];
|
||||
const bookNameIndex = bookList.indexOf(bookName);
|
||||
if (bookNameIndex >= 0) {
|
||||
bookListCopy.splice(bookNameIndex, 1);
|
||||
}
|
||||
return bookListCopy;
|
||||
}
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 9d7123c8c441eeafaeb5bdef
|
||||
title: splice の代わりに slice を使用して配列から要素を削除する
|
||||
challengeType: 1
|
||||
forumTopicId: 301236
|
||||
dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
配列の操作では、アイテムを削除して残りの配列を保持したいというパターンが一般的です。 そのための手段として、JavaScript には `splice` メソッドがあります。このメソッドは、アイテムの削除を開始するインデックスと、削除するアイテムの数を引数に取ります。 第 2 引数が指定されていない場合、デフォルトではアイテムが最後まで削除されます。 ただし、`splice` メソッドは呼び出しの対象となった元の配列をミューテート (変化) させます。 例を示します。
|
||||
|
||||
```js
|
||||
const cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
cities.splice(3, 1);
|
||||
```
|
||||
|
||||
この例では、`splice` は文字列 `London` を返し、それを cities 配列から削除します。 `cities` の値は `["Chicago", "Delhi", "Islamabad", "Berlin"]` になります。
|
||||
|
||||
前回のチャレンジで説明したように、 `slice` メソッドは元の配列をミューテートさせず、変数に保存できる新しい配列を返します。 すでに説明したように、`slice` メソッドは、スライスを開始するインデックスと終了するインデックス (終了場所はスライス対象には含まれません) を表す 2 つの引数を取り、それらのアイテムを新しい配列に返します。 `splice` の代わりに `slice` メソッドを使用すると、配列のミューテーションの副作用を回避できます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
関数 `nonMutatingSplice` を書き換えて、`splice` の代わりに `slice` を使用してください。 与えられた `cities` 配列の長さを 3 に制限し、最初の 3 つのアイテムのみを持つ新しい配列を返す必要があります。
|
||||
|
||||
関数に与えられた元の配列をミューテートさせないでください。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `slice` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
コードで `splice` メソッドを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?splice/g));
|
||||
```
|
||||
|
||||
`inputCities` 配列は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(inputCities) ===
|
||||
JSON.stringify(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` は `["Chicago", "Delhi", "Islamabad"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(
|
||||
nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
|
||||
) === JSON.stringify(['Chicago', 'Delhi', 'Islamabad'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
// Only change code below this line
|
||||
return cities.splice(3);
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
const inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
nonMutatingSplice(inputCities);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
return cities.slice(0,3);
|
||||
}
|
||||
const inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b6a
|
||||
title: 元の配列を変更せずにソートされた配列を返す
|
||||
challengeType: 1
|
||||
forumTopicId: 301237
|
||||
dashedName: return-a-sorted-array-without-changing-the-original-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`sort` メソッドには、元の配列にある要素の順序を変更するという副作用があります。 つまり、配列をインプレースでミューテートさせます。 これを避ける方法の一つとして、最初に空の配列をソート対象の配列に連結し (すでに説明したように `slice` や `concat` は新しい配列を返します)、それから `sort` メソッドを実行することができます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`nonMutatingSort` 関数で `sort` メソッドを使用して、配列の要素を昇順でソートしてください。 この関数は新しい配列を返し、`globalArray` 変数をミューテートさせないようにする必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `sort` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort.toString().match(/\.sort/g));
|
||||
```
|
||||
|
||||
`globalArray` 変数は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` は `[2, 3, 5, 6, 9]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingSort(globalArray)) ===
|
||||
JSON.stringify([2, 3, 5, 6, 9])
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` をハードコーディングしないでください。
|
||||
|
||||
```js
|
||||
assert(!nonMutatingSort.toString().match(/\[.*?[23569].*?\]/gs));
|
||||
```
|
||||
|
||||
この関数は、渡された配列ではなく、新しい配列を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort(globalArray) !== globalArray);
|
||||
```
|
||||
|
||||
`nonMutatingSort([1, 30, 4, 21, 100000])` は `[1, 4, 21, 30, 100000]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(nonMutatingSort([1, 30, 4, 21, 100000])) ===
|
||||
JSON.stringify([1, 4, 21, 30, 100000]))
|
||||
```
|
||||
|
||||
`nonMutatingSort([140000, 104, 99])` は `[99, 104, 140000]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(nonMutatingSort([140000, 104, 99])) ===
|
||||
JSON.stringify([99, 104, 140000]))
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
const globalArray = [5, 6, 3, 2, 9];
|
||||
|
||||
function nonMutatingSort(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
nonMutatingSort(globalArray);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const globalArray = [5, 6, 3, 2, 9];
|
||||
function nonMutatingSort(arr) {
|
||||
return [].concat(arr).sort((a,b) => a-b);
|
||||
}
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 587d7b90367417b2b2512b65
|
||||
title: slice メソッドを使用して配列の一部分を返す
|
||||
challengeType: 1
|
||||
forumTopicId: 301239
|
||||
dashedName: return-part-of-an-array-using-the-slice-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`slice` メソッドは、配列の特定の要素のコピーを返します。 このメソッドは 2 つの引数を取ることができます。1 つ目はスライスの開始位置のインデックスで、2 つ目はスライスの終了位置のインデックスです (終了位置自体は slice の対象に含まれません)。 引数が指定されていない場合は、デフォルトで配列の先頭から末尾まで処理します。この方法で配列全体のコピーを簡単に作成できます。 `slice` メソッドは元の配列をミューテート (変化) させず、新しい配列を返します。
|
||||
|
||||
例を示します。
|
||||
|
||||
```js
|
||||
const arr = ["Cat", "Dog", "Tiger", "Zebra"];
|
||||
const newArray = arr.slice(1, 3);
|
||||
```
|
||||
|
||||
`newArray` の値は `["Dog", "Tiger"]` になります。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`sliceArray` 関数で `slice` メソッドを使用し、`beginSlice` インデックスと `endSlice` インデックスを指定して `anim` 配列の一部を返してください。 この関数は配列を返す必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `slice` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
`inputAnim` 変数は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(inputAnim) ===
|
||||
JSON.stringify(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` は `["Dog", "Tiger"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)) ===
|
||||
JSON.stringify(['Dog', 'Tiger'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` は `["Cat"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)) ===
|
||||
JSON.stringify(['Cat'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` は `["Dog", "Tiger", "Zebra"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)) ===
|
||||
JSON.stringify(['Dog', 'Tiger', 'Zebra'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
const inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
sliceArray(inputAnim, 1, 3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
return anim.slice(beginSlice, endSlice);
|
||||
}
|
||||
const inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b69
|
||||
title: sort メソッドを使用して配列をアルファベット順に並べ替える
|
||||
challengeType: 1
|
||||
forumTopicId: 18303
|
||||
dashedName: sort-an-array-alphabetically-using-the-sort-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`sort` メソッドは、コールバック関数に従って配列の要素をソートします。
|
||||
|
||||
例を次に示します。
|
||||
|
||||
```js
|
||||
function ascendingOrder(arr) {
|
||||
return arr.sort(function(a, b) {
|
||||
return a - b;
|
||||
});
|
||||
}
|
||||
|
||||
ascendingOrder([1, 5, 2, 3, 4]);
|
||||
```
|
||||
|
||||
これは値 `[1, 2, 3, 4, 5]` を返します。
|
||||
|
||||
```js
|
||||
function reverseAlpha(arr) {
|
||||
return arr.sort(function(a, b) {
|
||||
return a === b ? 0 : a < b ? 1 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
reverseAlpha(['l', 'h', 'z', 'b', 's']);
|
||||
```
|
||||
|
||||
これは値 `['z', 's', 'l', 'h', 'b']` を返します。
|
||||
|
||||
JavaScript のデフォルトのソート方法で基準となるのは文字列の Unicode ポイント値であり、予期しない結果を返す可能性があります。 そのため、配列アイテムのソート方法を指定するコールバック関数を用意することをお勧めします。 コールバック関数には通常は `compareFunction` などという名前を付けますが、そうしたコールバック関数を指定すると、`compareFunction` の戻り値に従って配列要素がソートされます。たとえば、`compareFunction(a,b)` が 2 つの要素 `a` と `b` に対して 0 よりも小さい値を返した場合、`a` は `b` の前になります。 `compareFunction(a,b)` が 2 つの要素 `a` と `b` に対して 0 よりも大きい値を返した場合、`b` は `a` の前になります。 `compareFunction(a,b)` が 2 つの要素 `a` と `b` に対して 0 と等しい値を返した場合、`a` と `b` の順序は変わりません。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`alphabeticalOrder` 関数で `sort` メソッドを使用して、`arr` の要素をアルファベット順にソートしてください。 この関数はソートされた配列を返す必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `sort` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.sort/g));
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` は `["a", "a", "c", "d", "g", "z"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])) ===
|
||||
JSON.stringify(['a', 'a', 'c', 'd', 'g', 'z'])
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` は `["a", "h", "m", "m", "n", "x"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])) ===
|
||||
JSON.stringify(['a', 'h', 'm', 'm', 'n', 'x'])
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` は `["a", "a", "a", "a", "t", "x"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])) ===
|
||||
JSON.stringify(['a', 'a', 'a', 'a', 't', 'x'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
return arr
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
return arr.sort();
|
||||
}
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6b
|
||||
title: split メソッドを使用して文字列を配列に分割する
|
||||
challengeType: 1
|
||||
forumTopicId: 18305
|
||||
dashedName: split-a-string-into-an-array-using-the-split-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`split` メソッドは、文字列を文字列の配列に分割します。 このメソッドは、文字列や正規表現の分割に使用できる区切り文字の引数を取ります。 たとえば、区切り文字が空白の場合は、単語の配列を取得します。 区切り文字が空文字列の場合は、文字列内の各文字で構成される配列を取得します。
|
||||
|
||||
2 つの例を次に示します。1 つ目は文字列をスペースで分割し、2 つ目は正規表現を使用して文字列を数字で分割します。
|
||||
|
||||
```js
|
||||
const str = "Hello World";
|
||||
const bySpace = str.split(" ");
|
||||
|
||||
const otherString = "How9are7you2today";
|
||||
const byDigits = otherString.split(/\d/);
|
||||
```
|
||||
|
||||
`bySpace` の値は `["Hello", "World"]` になり、`byDigits` の値は `["How", "are", "you", "today"]` になります。
|
||||
|
||||
文字列はイミュータブル (不変) なので、`split` メソッドを使用すると文字列を簡単に操作できます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`splitify` 関数の中で `split` メソッドを使用して、`str` を単語の配列に分割してください。 この関数は配列を返す必要があります。 単語は必ずしもスペースで区切られているとは限らず、配列に句読点を含めてはならないことに注意してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `split` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.split/g));
|
||||
```
|
||||
|
||||
`splitify("Hello World,I-am code")` は `["Hello", "World", "I", "am", "code"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('Hello World,I-am code')) ===
|
||||
JSON.stringify(['Hello', 'World', 'I', 'am', 'code'])
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("Earth-is-our home")` は `["Earth", "is", "our", "home"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('Earth-is-our home')) ===
|
||||
JSON.stringify(['Earth', 'is', 'our', 'home'])
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("This.is.a-sentence")` は `["This", "is", "a", "sentence"]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('This.is.a-sentence')) ===
|
||||
JSON.stringify(['This', 'is', 'a', 'sentence'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
splitify("Hello World,I-am code");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
return str.split(/\W/);
|
||||
}
|
||||
```
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5c
|
||||
title: 関数型プログラミングの用語を理解する
|
||||
challengeType: 1
|
||||
forumTopicId: 301240
|
||||
dashedName: understand-functional-programming-terminology
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
FCC のチームの気が変わって、今は緑茶と紅茶の 2 種類のお茶が欲しくなりました。 クライアントの気が変わるというのは一般的な事実としてよくあることです。
|
||||
|
||||
そんな情報を踏まえて、前回のチャレンジで取り上げた `getTea` 関数を見直して、さまざまなお茶のリクエストを処理する必要が出てきました。 パラメーターとして関数を受け取るように `getTea` を変更して、用意するお茶の種類を変えることができます。 これで `getTea` の柔軟性が増し、クライアントのリクエストが変更されたときにプログラマーはより詳細に制御できるようになります。
|
||||
|
||||
ですがその前に、関数型に関する用語をいくつか説明しておきましょう。
|
||||
|
||||
ある関数の呼び出しを決定するために挿入されたり渡されたりする関数のことを、<dfn>コールバック</dfn>と呼びます。 たとえば `filter` などの他のメソッドにコールバック関数を渡す例を紹介しました。この場合は、フィルターで配列を絞り込むための条件を JavaScript に指示します。
|
||||
|
||||
変数に割り当てることができる関数、別の関数に渡すことができる関数、または別の関数から他の通常の値とまったく同じように返すことができる関数のことを、<dfn>第一級</dfn>関数と呼びます。 JavaScript の関数はすべて第一級関数です。
|
||||
|
||||
引数として関数を受け取る関数、または戻り値として関数を返す関数のことを、<dfn>高階</dfn>関数と呼びます。
|
||||
|
||||
関数が他の関数に渡されたり、他の関数から返されたりする場合、それらの受け渡しされる関数のことを<dfn>ラムダ</dfn>と呼ぶことがあります。
|
||||
|
||||
# --instructions--
|
||||
|
||||
緑茶を 27 杯分、紅茶を 13 杯分用意し、それぞれ `tea4GreenTeamFCC` と `tea4BlackTeamFCC` という変数に保存してください。 `getTea` 関数を変更したので、最初の引数として関数を取ることに注意してください。
|
||||
|
||||
注: データ (お茶のカップ数) は最後の引数として渡します。 これについてはこのあとのレッスンで詳しく説明します。
|
||||
|
||||
# --hints--
|
||||
|
||||
`tea4GreenTeamFCC` 変数は、チーム用に 27 杯分の緑茶を保持する必要があります。
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC.length === 27);
|
||||
```
|
||||
|
||||
`tea4GreenTeamFCC` 変数は、緑茶のカップを保持する必要があります。
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
`tea4BlackTeamFCC` 変数は、13 杯分の紅茶を保持する必要があります。
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC.length === 13);
|
||||
```
|
||||
|
||||
`tea4BlackTeamFCC` 変数は、紅茶のカップを保持する必要があります。
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC[0] === 'blackTea');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Function that returns a string representing a cup of green tea
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
|
||||
// Function that returns a string representing a cup of black tea
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
/*
|
||||
Given a function (representing the tea type) and number of cups needed, the
|
||||
following function returns an array of strings (each representing a cup of
|
||||
a specific type of tea).
|
||||
*/
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
const tea4GreenTeamFCC = null;
|
||||
const tea4BlackTeamFCC = null;
|
||||
// Only change code above this line
|
||||
|
||||
console.log(
|
||||
tea4GreenTeamFCC,
|
||||
tea4BlackTeamFCC
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
const tea4BlackTeamFCC = getTea(prepareBlackTea, 13);
|
||||
const tea4GreenTeamFCC = getTea(prepareGreenTea, 27);
|
||||
```
|
@ -0,0 +1,139 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5d
|
||||
title: 命令型コードの使用に関する危険性を理解する
|
||||
challengeType: 1
|
||||
forumTopicId: 301241
|
||||
dashedName: understand-the-hazards-of-using-imperative-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
関数型プログラミングは良い習慣です。 コードが管理しやすくなり、バグの潜入を防ぎます。 しかし、そうした習慣に行き着く前に、命令型プログラミングのアプローチについて、問題が起こりそうな場所を明らかにしておきましょう。
|
||||
|
||||
英語 (および他の多くの言語) では、コマンドを与えるために命令型の時制が使用されています。 同様に、プログラミングにおける命令型のスタイルは、コンピューターにタスクを実行するための一連のステートメントを与えます。
|
||||
|
||||
多くの場合、ステートメントはプログラムの状態を変更し、グローバル変数を更新したりします。 典型的な例としては、`for` ループの記述で配列のインデックスを反復処理するための正確な方向を示すことなどがあります。
|
||||
|
||||
対照的に、関数型プログラミングは宣言型プログラミングの一形態です。 メソッドや関数を呼び出すことによって、実行したいことをコンピューターに伝えます。
|
||||
|
||||
JavaScript には、一般的なタスクを処理するためにあらかじめ定義されたメソッドが多数用意されているため、コンピューターがそれらのタスクをどのように実行すべきかを記述する必要はありません。 たとえば、前述の `for` ループを使用する代わりに、配列の反復の詳細を処理する `map` メソッドを呼び出すことができます。 これは、「デバッグ」セクションで説明した「オフバイワンエラー」などのセマンティックエラーを回避するのに役立ちます。
|
||||
|
||||
たとえば、ブラウザーでウェブを閲覧していて、開いたタブを追跡したい、というシナリオを考えてみましょう。 簡単なオブジェクト指向のコードを使ってそれをモデル化してみます。
|
||||
|
||||
Window オブジェクトはタブで構成されており、通常は複数の Window が開いています。 各 Window オブジェクトで開いているそれぞれのサイトのタイトルを、配列に保持しています。 ブラウザーで作業した後 (新しいタブを開く、ウィンドウをマージする、タブを閉じるなど)、まだ開いているタブを印刷する必要があるとします。 閉じたタブを配列から削除し、新しいタブを末尾に追加します (説明を簡単にするため)。
|
||||
|
||||
コードエディターでは、`tabOpen()`、`tabClose()`、および `join()` に対応した関数を使用して、この機能を実装しています。 配列 `tabs` は、開いているページの名前を格納する Window オブジェクトの一部です。
|
||||
|
||||
# --instructions--
|
||||
|
||||
エディターでコードの内容を調べてみてください。 この中ではプログラムに副作用をもたらすメソッドを使用しており、不正な動作を引き起こします。 `finalTabs.tabs` に格納される、開いているタブの最終的なリストは、`['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` となるはずですが、コードによって生成されるリストは少し異なります。
|
||||
|
||||
正しいタブが削除されるように `Window.prototype.tabClose` を変更してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
`finalTabs.tabs` は `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` となる必要があります。
|
||||
|
||||
```js
|
||||
assert.deepEqual(finalTabs.tabs, [
|
||||
'FB',
|
||||
'Gitter',
|
||||
'Reddit',
|
||||
'Twitter',
|
||||
'Medium',
|
||||
'new tab',
|
||||
'Netflix',
|
||||
'YouTube',
|
||||
'Vine',
|
||||
'GMail',
|
||||
'Work mail',
|
||||
'Docs',
|
||||
'freeCodeCamp',
|
||||
'new tab'
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// tabs is an array of titles of each site open within the window
|
||||
const Window = function(tabs) {
|
||||
this.tabs = tabs; // We keep a record of the array inside the object
|
||||
};
|
||||
|
||||
// When you join two windows into one window
|
||||
Window.prototype.join = function(otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you open a new tab at the end
|
||||
Window.prototype.tabOpen = function(tab) {
|
||||
this.tabs.push('new tab'); // Let's open a new tab for now
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you close a tab
|
||||
Window.prototype.tabClose = function(index) {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
const tabsBeforeIndex = this.tabs.splice(0, index); // Get the tabs before the tab
|
||||
const tabsAfterIndex = this.tabs.splice(index + 1); // Get the tabs after the tab
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Let's create three browser windows
|
||||
const workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
|
||||
const socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
|
||||
const videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
|
||||
|
||||
// Now perform the tab opening, closing, and other operations
|
||||
const finalTabs = socialWindow
|
||||
.tabOpen() // Open a new tab for cat memes
|
||||
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
console.log(finalTabs.tabs);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const Window = function(tabs) {
|
||||
this.tabs = tabs;
|
||||
};
|
||||
|
||||
Window.prototype.join = function(otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
Window.prototype.tabOpen = function(tab) {
|
||||
this.tabs.push('new tab');
|
||||
return this;
|
||||
};
|
||||
|
||||
Window.prototype.tabClose = function(index) {
|
||||
const tabsBeforeIndex = this.tabs.slice(0, index);
|
||||
const tabsAfterIndex = this.tabs.slice(index + 1);
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex);
|
||||
return this;
|
||||
};
|
||||
|
||||
const workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']);
|
||||
const socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']);
|
||||
const videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']);
|
||||
|
||||
const finalTabs = socialWindow
|
||||
.tabOpen()
|
||||
.join(videoWindow.tabClose(2))
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
```
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b45
|
||||
title: '高階関数 map、filter、または reduce を使用して複雑な問題を解決する'
|
||||
challengeType: 1
|
||||
forumTopicId: 301311
|
||||
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
ここまで、`map()`、`filter()`、`reduce()` のような高階関数を使用したいくつかのチャレンジに取り組んできました。これらを応用して、より複雑なチャレンジを解決してみましょう。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`map()`、`filter()`、`reduce()` を自由に組み合わせて `squareList` 関数のコードを完成させてください。 この関数は、実数の配列が渡されたときに、正の整数*のみ* (小数は整数ではありません) についてその 2 乗を含む新しい配列を返す必要があります。 実数の配列の例は、`[-3, 4.8, 5, 3, -3.2]` などとなります。
|
||||
|
||||
**注:** 関数ではどのような `for` ループや `while` ループ、または `forEach()` 関数も使用してはいけません。
|
||||
|
||||
# --hints--
|
||||
|
||||
`squareList` は `function` である必要があります。
|
||||
|
||||
```js
|
||||
assert.typeOf(squareList, 'function'),
|
||||
'<code>squareList</code> should be a <code>function</code>';
|
||||
```
|
||||
|
||||
`for`、`while`、および `forEach` は使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/for|while|forEach/g));
|
||||
```
|
||||
|
||||
`map`、`filter`、または `reduce` を使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers
|
||||
.removeWhiteSpace(code)
|
||||
.match(/\.(map|filter|reduce)\(/g)
|
||||
);
|
||||
```
|
||||
|
||||
この関数は `array` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
|
||||
```
|
||||
|
||||
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` は `[16, 1764, 36]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
|
||||
16,
|
||||
1764,
|
||||
36
|
||||
]);
|
||||
```
|
||||
|
||||
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` は `[9, 100, 49]` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [
|
||||
9,
|
||||
100,
|
||||
49
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
const squareList = arr => {
|
||||
// Only change code below this line
|
||||
return arr;
|
||||
// Only change code above this line
|
||||
};
|
||||
|
||||
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
|
||||
console.log(squaredIntegers);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const squareList = arr => {
|
||||
const positiveIntegers = arr.filter(num => {
|
||||
return num >= 0 && Number.isInteger(num);
|
||||
});
|
||||
const squaredIntegers = positiveIntegers.map(num => {
|
||||
return num ** 2;
|
||||
});
|
||||
return squaredIntegers;
|
||||
};
|
||||
```
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6e
|
||||
title: every メソッドを使用して、配列内のすべての要素が基準を満たしていることを確認する
|
||||
challengeType: 1
|
||||
forumTopicId: 301312
|
||||
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`every` メソッドは配列で動作し、*すべての*要素が特定のテストを満たすかどうかを調べます。 すべての値が基準を満たしている場合は、ブール値 `true` を返します。そうでない場合は、`false` を返します。
|
||||
|
||||
たとえば、次のコードは `numbers` 配列のすべての要素が 10 未満であるかどうかを確認します。
|
||||
|
||||
```js
|
||||
const numbers = [1, 5, 8, 0, 10, 11];
|
||||
|
||||
numbers.every(function(currentValue) {
|
||||
return currentValue < 10;
|
||||
});
|
||||
```
|
||||
|
||||
この例では `every` メソッドは `false` を返します。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`checkPositive` 関数の中で `every` メソッドを使用して、`arr` 内のすべての要素が正の値かどうかを調べてください。 関数はブール値を返す必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `every` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.every/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` は `false` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` は `true` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, -2, 3, -4, 5])` は `false` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
return arr.every(num => num > 0);
|
||||
}
|
||||
```
|
@ -0,0 +1,314 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b63
|
||||
title: filter メソッドを使用して配列からデータを抽出する
|
||||
challengeType: 1
|
||||
forumTopicId: 18179
|
||||
dashedName: use-the-filter-method-to-extract-data-from-an-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
もう一つの便利な配列関数に、`Array.prototype.filter()`、または単に `filter()` があります。
|
||||
|
||||
`filter` は配列の各要素に対して関数を呼び出し、その関数が `true` を返す要素のみを含む新しい配列を返します。 つまり、渡された関数に基づいて配列をフィルターで絞り込みます。 `map` と同様に、元の配列を変更せずにこうした操作を実行します。
|
||||
|
||||
コールバック関数は 3 つの引数を受け取ります。 最初の引数は、現在処理中の要素です。 2 つ目は、その要素のインデックスです。3 つ目は、`filter` メソッドを呼び出した対象の配列です。
|
||||
|
||||
次の例では、`users` 配列で `filter` メソッドを使用して、30 歳未満のユーザーのみを含む新しい配列を返しています。 簡単のため、この例ではコールバックの最初の引数のみを使用しています。
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const usersUnder30 = users.filter(user => user.age < 30);
|
||||
console.log(usersUnder30);
|
||||
```
|
||||
|
||||
コンソールには値 `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]` が表示されます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
変数 `watchList` に、複数のムービーに関する情報を持つオブジェクトの配列が保持されています。 `watchList` に対して `filter` と `map` を組み合わせて使用し、`title` キーと `rating` キーのみを持つオブジェクトの新しい配列を割り当ててください。 新しい配列には、`imdbRating` が 8.0 以上のオブジェクトのみを含める必要があります。 `rating` の値はオブジェクトに文字列として保存され、算術演算を実行する場合は数値に変換する必要があることに注意してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
`watchList` 変数は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
コードで `filter` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\s*\.\s*filter/g));
|
||||
```
|
||||
|
||||
コードで `for` ループを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
`filteredList` は `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"}, {"title": "Batman Begins", "rating": "8.3"}]` と等しくなる必要があります。
|
||||
|
||||
```js
|
||||
assert.deepEqual(filteredList, [
|
||||
{ title: 'Inception', rating: '8.8' },
|
||||
{ title: 'Interstellar', rating: '8.6' },
|
||||
{ title: 'The Dark Knight', rating: '9.0' },
|
||||
{ title: 'Batman Begins', rating: '8.3' }
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
const filteredList = "";
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(filteredList);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
const filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
```
|
@ -0,0 +1,329 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b61
|
||||
title: map メソッドを使用して配列からデータを抽出する
|
||||
challengeType: 1
|
||||
forumTopicId: 18214
|
||||
dashedName: use-the-map-method-to-extract-data-from-an-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
ここまで、プログラムの副作用を回避するために純粋な関数を使用することを学んできました。 また、関数を使用する場合の値は入力の引数にのみ依存することを説明しました。
|
||||
|
||||
これは始まりにすぎません。 その名前が示すように、関数型プログラミングは関数の理論を中心としています。
|
||||
|
||||
関数を引数として他の関数に渡せること、そして別の関数から関数を返せることは、理にかなっています。 JavaScript では関数は<dfn>第一級オブジェクト</dfn>とみなされます。つまり、他のオブジェクトと同じように扱うことができ、 変数に保存したり、オブジェクトに格納したり、関数引数として渡したりすることができます。
|
||||
|
||||
まず、配列オブジェクトのプロトタイプのメソッドであるいくつかの簡単な配列関数から説明しましょう。 この課題では、`Array.prototype.map()`、またはより単純な `map` を取り上げます。
|
||||
|
||||
`map` メソッドは、配列内の各アイテムを反復処理し、各要素についてコールバック関数を呼び出した結果を含む新しい配列を返します。 この操作は元の配列をミューテート (変化) させずに行われます。
|
||||
|
||||
コールバックを使用するときは、3 つの引数を渡します。 最初の引数は、現在処理中の要素です。 2 つ目は、その要素のインデックスです。3 つ目は、`map` メソッドを呼び出した対象の配列です。
|
||||
|
||||
次の例では、`users` 配列で `map` メソッドを使用して、ユーザーの名前のみを要素として含む新しい配列を返しています。 簡単のため、この例ではコールバックの最初の引数のみを使用しています。
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const names = users.map(user => user.name);
|
||||
console.log(names);
|
||||
```
|
||||
|
||||
コンソールには値 `[ 'John', 'Amy', 'camperCat' ]` が表示されます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`watchList` 配列に、複数のムービーに関する情報を持つオブジェクトが保持されています。 `watchList` で `map` を使用して、`ratings` 変数にオブジェクトの新しい配列を割り当ててください。 新しい配列の各ムービーには、ムービーの名前を表す `title` キーと、IMDB でのレーティングを表す `rating` キーのみが存在する必要があります。 エディターの現在のコードでは、これを実行するために `for` ループを使用しているため、このループ機能を `map` 式に置き換える必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
`watchList` 変数は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
`for` ループを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/));
|
||||
```
|
||||
|
||||
コードで `map` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.map/g));
|
||||
```
|
||||
|
||||
`ratings` は `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"},{"title": "Batman Begins", "rating": "8.3"}, {"title": "Avatar", "rating": "7.9"}]` と等しくなる必要があります。
|
||||
|
||||
```js
|
||||
assert.deepEqual(ratings, [
|
||||
{ title: 'Inception', rating: '8.8' },
|
||||
{ title: 'Interstellar', rating: '8.6' },
|
||||
{ title: 'The Dark Knight', rating: '9.0' },
|
||||
{ title: 'Batman Begins', rating: '8.3' },
|
||||
{ title: 'Avatar', rating: '7.9' }
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
const ratings = [];
|
||||
for (let i = 0; i < watchList.length; i++) {
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(JSON.stringify(ratings));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
const ratings = watchList.map(function(movie) {
|
||||
return {
|
||||
title: movie["Title"],
|
||||
rating: movie["imdbRating"]
|
||||
}
|
||||
});
|
||||
```
|
@ -0,0 +1,345 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b68
|
||||
title: reduce メソッドを使用してデータを分析する
|
||||
challengeType: 1
|
||||
forumTopicId: 301313
|
||||
dashedName: use-the-reduce-method-to-analyze-data
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`Array.prototype.reduce()`、または単に `reduce()` は、JavaScript のすべての配列操作の中で最も一般的なものです。 `reduce` メソッドを使用すると、ほぼすべての配列処理の問題を解決できます。
|
||||
|
||||
`reduce` メソッドでは、より一般的な形式の配列処理が可能であり、`filter` および `map` の両方が `reduce` の特別な応用として導かれることを示すことができます。 `reduce` メソッドは、配列内の各アイテムを反復処理し、単一の値 (文字列、数値、オブジェクト、配列など) を返します。 これは、各反復で呼び出されるコールバック関数によって実現されます。
|
||||
|
||||
コールバック関数は 4 つの引数を受け取ります。 最初の引数はアキュムレーターと呼ばれ、前の反復からのコールバック関数の戻り値が割り当てられます。2 つ目は現在処理されている要素で、3 つ目はその要素のインデックス、そして 4つ目は `reduce` が呼び出された対象の配列です。
|
||||
|
||||
コールバック関数に加えて、`reduce` にはアキュムレーターの初期値を受け取る追加のパラメーターがあります。 この 2 番目のパラメーターが使用されていない場合、1 回目の反復はスキップされ、2 回目の反復がアキュムレーターとして配列の最初の要素に渡されます。
|
||||
|
||||
`users` 配列で `reduce` を使用してすべてのユーザーの年齢の合計を返す例を次に示します。 簡単のため、この例では最初と 2 つ目の引数のみを使用しています。
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
|
||||
console.log(sumOfAges);
|
||||
```
|
||||
|
||||
コンソールには値 `64` が表示されます。
|
||||
|
||||
次の例は、ユーザーの名前をプロパティとして含み、年齢を値として含むオブジェクトを返します。
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const usersObj = users.reduce((obj, user) => {
|
||||
obj[user.name] = user.age;
|
||||
return obj;
|
||||
}, {});
|
||||
console.log(usersObj);
|
||||
```
|
||||
|
||||
コンソールには値 `{ John: 34, Amy: 20, camperCat: 10 }` が表示されます。
|
||||
|
||||
# --instructions--
|
||||
|
||||
変数 `watchList` に、複数のムービーに関する情報を持つオブジェクトの配列が保持されています。 `reduce` を使用して、`Christopher Nolan` が監督する映画の平均の IMDB 評価を調べてください。 以前のチャレンジで、データを `filter` したり `map` 処理したりして必要なものを引き出す方法を説明しましたが、それらを参考にしてください。 他の変数を作成し、`getRating` 関数から平均評価を返す必要があるかもしれません。 評価の値はオブジェクトに文字列として保存され、算術演算で使用する場合はその前に数値に変換する必要があることに注意してください。
|
||||
|
||||
# --hints--
|
||||
|
||||
`watchList` 変数は変更しないでください。
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
コードで `reduce` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.reduce/g));
|
||||
```
|
||||
|
||||
`getRating(watchList)` は 8.675 になる必要があります。
|
||||
|
||||
```js
|
||||
assert(getRating(watchList) === 8.675);
|
||||
```
|
||||
|
||||
コードで `for` ループを使用しないでください。
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
`watchList` オブジェクトを変更した後、コードは正しい出力を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
function getRating(watchList) {
|
||||
// Only change code below this line
|
||||
let averageRating;
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return averageRating;
|
||||
}
|
||||
|
||||
console.log(getRating(watchList));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
function getRating(watchList) {
|
||||
let averageRating;
|
||||
const rating = watchList
|
||||
.filter(obj => obj.Director === "Christopher Nolan")
|
||||
.map(obj => Number(obj.imdbRating));
|
||||
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
|
||||
return averageRating;
|
||||
}
|
||||
```
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6f
|
||||
title: some メソッドを使用して、配列内のいずれかの要素が基準を満たしていることを確認する
|
||||
challengeType: 1
|
||||
forumTopicId: 301314
|
||||
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`some` メソッドは配列と連携して機能し、*いずれかの*要素が特定のテストを満たすかどうかを調べます。 いずれかの値が基準を満たしている場合は、ブール値 `true` を返します。そうでない場合は、`false` を返します。
|
||||
|
||||
たとえば、次のコードは `numbers` 配列のいずれかの要素が 10 未満であるかどうかを調べます。
|
||||
|
||||
```js
|
||||
const numbers = [10, 50, 8, 220, 110, 11];
|
||||
|
||||
numbers.some(function(currentValue) {
|
||||
return currentValue < 10;
|
||||
});
|
||||
```
|
||||
|
||||
`some` メソッドは `true` を返します。
|
||||
|
||||
# --instructions--
|
||||
|
||||
`checkPositive` 関数の中で `some` メソッドを使用して、`arr` 内のいずれかの要素が正かどうかを調べてください。 この関数はブール値を返す必要があります。
|
||||
|
||||
# --hints--
|
||||
|
||||
コードで `some` メソッドを使用する必要があります。
|
||||
|
||||
```js
|
||||
assert(code.match(/\.some/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` は `true` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` は `true` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([-1, -2, -3, -4, -5])` は `false` を返す必要があります。
|
||||
|
||||
```js
|
||||
assert(!checkPositive([-1, -2, -3, -4, -5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
return arr.some(elem => elem > 0);
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user