學習軌道
/
JavaScript
JavaScript
/
練習
/
Ozan 的播放清單
Ozan 的播放清單

Ozan 的播放清單

學習練習

簡介

在 JavaScript 中,集合是一種類似清單的結構,內含不重複的值,這些值可以是基本型別,也可以是物件參照。和陣列不同,集合的元素無法透過索引存取。

如果某個值和集合中任何一個元素嚴格相等,就無法加入該集合。

const set = new Set();
const object = { color: 'lime green' };
const functionallyIdenticalObject = { color: 'lime green' };

set.add(object);
set.add('wow');
set.add(77);

console.log(set.size);
//=> 3

set.add(functionallyIdenticalObject); // added because functionallyIdenticalObject is not strictly equal to object
console.log(set.size);
//=> 4

set.add(77); // not added because 77 is strictly equal to 77
console.log(set.size);
//=> 4

建立集合時,你可以傳入陣列作為引數,陣列中的值會成為集合的值,重複的值也會一併移除。

const array = [1, 5, 4, 1];
const set = new Set(array); // the set's values become [1, 5, 4]

console.log(set.size);
//=> 3

若要將集合轉成陣列,可以使用 Array.from(),它能把可迭代物件(例如集合或映射)轉成陣列。

const set = new Set();

set.add(1);
set.add(2);
set.add(3);
set.add(4);

const array = Array.from(set);
console.log(array);
//=> [1, 2, 3, 4]

說明

Ozan 正在為即將到來的公路旅行整理播放清單。他不想再聽到重複的曲目,但這份清單已經長到他記不清哪些曲目早就加進去了。

Ozan 的音樂播放器 API 只懂得處理陣列,於是他試著寫一些程式碼,用Array.indexOf()在把曲目加進播放清單前先檢查它是否已經存在。可惜的是,他的程式執行起來實在太慢了。他需要你的幫忙!

你出手相助,卻驚訝地發現他的播放清單裡有_五十萬_首曲目。也許你知道某種不同的資料結構,能讓你更有效率地操作這份播放清單?

1. 移除重複的曲目

實作removeDuplicates函式,它接受一份播放清單作為_參數_,並_回傳_一份所有曲目都不重複的新播放清單。

const playlist = [
  'Court and Spark - Joni Mitchell',
  'Big Yellow Taxi - Joni Mitchell',
  'Court and Spark - Joni Mitchell',
];

removeDuplicates(playlist);
//=> ['Court and Spark - Joni Mitchell', 'Big Yellow Taxi - Joni Mitchell']

2. 檢查曲目是否已經加過

實作hasTrack函式,它接受一份播放清單和一首曲目作為_參數_,並_回傳_一個布林值,指出播放清單是否包含這首曲目。

const playlist = [
  'The Fashion Show - Grace Jones',
  'Dr. Funkenstein - Parliament',
];

hasTrack(playlist, 'Dr. Funkenstein - Parliament');
//=> true

hasTrack(playlist, 'Walking in the Rain - Grace Jones');
//=> false

3. 新增曲目

實作addTrack函式,它接受一份播放清單和一首曲目作為_參數_,並_回傳_一份包含這首曲目的新播放清單。

const playlist = ['Selma - Bijelo Dugme'];

addTrack(playlist, 'Atomic Dog - George Clinton');
//=> ['Selma - Bijelo Dugme', 'Atomic Dog - George Clinton']

addTrack(playlist, 'Selma - Bijelo Dugme');
//=> ['Selma - Bijelo Dugme', 'Atomic Dog - George Clinton']

4. 刪除曲目

實作deleteTrack函式,它接受一份播放清單和一首曲目作為_參數_,並_回傳_一份不包含這首曲目的新播放清單。

const playlist = [
  'The Treasure - Fra Lippo Lippi',
  'After the Fall - Klaus Nomi',
];

deleteTrack(playlist, 'The Treasure - Fra Lippo Lippi');
//=> ['After the Fall - Klaus Nomi']

deleteTrack(playlist, 'I Feel the Magic - Belinda Carlisle');
//=> ['After the Fall - Klaus Nomi']

5. 列出不重複的演出者

實作listArtists函式,它接受一份播放清單作為_參數_,並_回傳_播放清單中所有不重複演出者的清單。請注意,曲目的名稱格式為<SONG> - <ARTIST>。

const playlist = [
  'All Mine - Portishead',
  'Sight to Behold - Devendra Banhart',
  'Sour Times - Portishead',
];

listArtists(playlist);
//=> ['Portishead', 'Devendra Banhart']
透過 GitHub 編輯 連結會在新視窗或分頁中開啟
JavaScript Exercism

準備好開始 Ozan 的播放清單 了嗎?

註冊 Exercism,透過 37 個概念159 個練習 和真人引導來學習並精通 JavaScript,全部免費。