diff --git a/src/ageClassification.test.ts b/src/ageClassification.test.ts new file mode 100644 index 0000000..07ec85d --- /dev/null +++ b/src/ageClassification.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from 'vitest'; +import { classifyAge } from './ageClassification'; + +describe('年齡分類函式測試', () => { + it('應將 12 歲以下分類為 Child', () => { + expect(classifyAge(10)).toBe('Child'); + }); + + it('應將 13 至 17 歲分類為 Teenager', () => { + expect(classifyAge(15)).toBe('Teenager'); + }); + + it('應將 18 至 64 歲分類為 Adult', () => { + expect(classifyAge(30)).toBe('Adult'); + }); + + it('應將 65 歲以上分類為 Senior', () => { + expect(classifyAge(70)).toBe('Senior'); + }); +}); \ No newline at end of file diff --git a/src/ageClassification.ts b/src/ageClassification.ts new file mode 100644 index 0000000..febc78d --- /dev/null +++ b/src/ageClassification.ts @@ -0,0 +1,23 @@ +/** + * 任務:實作一個函式 `classifyAge`,根據年齡進行分類。 + * + * 範例: + * classifyAge(10) 應該回傳 "Child" + * classifyAge(15) 應該回傳 "Teenager" + * classifyAge(30) 應該回傳 "Adult" + * classifyAge(70) 應該回傳 "Senior" + * + * @param age - 一個需要被分類的年齡 + * @returns - 回傳年齡的分類結果 + */ +export function classifyAge(age: number): string { + if (age >= 0 && age < 15){ + return 'Child'; + }else if (age >= 15 && age < 30){ + return 'Teenager'; + }else if (age >= 30 && age < 70){ + return 'Adult'; + }else{ + return 'Senior'; + } +} \ No newline at end of file diff --git a/src/arrayFiltering.test.ts b/src/arrayFiltering.test.ts new file mode 100644 index 0000000..0e804cd --- /dev/null +++ b/src/arrayFiltering.test.ts @@ -0,0 +1,8 @@ +import { describe, it, expect } from 'vitest'; +import { filterEvens } from './arrayFiltering'; + +describe('陣列過濾函式測試', () => { + it('應該過濾出偶數', () => { + expect(filterEvens([1, 2, 3, 4, 5])).toEqual([2, 4]); + }); +}); \ No newline at end of file diff --git a/src/arrayFiltering.ts b/src/arrayFiltering.ts new file mode 100644 index 0000000..a363826 --- /dev/null +++ b/src/arrayFiltering.ts @@ -0,0 +1,13 @@ +/** + * 任務:實作一個函式 `filterEvens`,過濾出數字陣列中的偶數。 + * + * 範例: + * filterEvens([1, 2, 3, 4]) 應該回傳 [2, 4] + * filterEvens([5, 6, 7, 8]) 應該回傳 [6, 8] + * + * @param numbers - 一個需要被過濾的數字陣列 + * @returns - 回傳只包含偶數的數字陣列 + */ +export function filterEvens(numbers: number[]): number[] { + return numbers.filter((item) => item % 2 === 0 ); +} \ No newline at end of file diff --git a/src/arraySum.ts b/src/arraySum.ts index b0248ce..dc147ec 100644 --- a/src/arraySum.ts +++ b/src/arraySum.ts @@ -14,4 +14,9 @@ */ export function arraySum(numbers: number[]): number { // 在此實現函式 + let total: number = 0; + for (let i = 0; i < numbers.length; i++) { + total = total + numbers[i]; + } + return total; } \ No newline at end of file diff --git a/src/asyncSum.test.ts b/src/asyncSum.test.ts new file mode 100644 index 0000000..3cbd1a7 --- /dev/null +++ b/src/asyncSum.test.ts @@ -0,0 +1,14 @@ +import { describe, it, expect } from 'vitest'; +import { asyncSum } from './asyncSum'; + +describe('非同步加總函式', () => { + it('應該能計算陣列中所有數字的總和', async () => { + const result = await asyncSum([1, 2, 3, 4, 5]); + expect(result).toBe(15); + }); + + it('應該能正確處理空陣列', async () => { + const result = await asyncSum([]); + expect(result).toBe(0); + }); +}); \ No newline at end of file diff --git a/src/asyncSum.ts b/src/asyncSum.ts new file mode 100644 index 0000000..3b2642f --- /dev/null +++ b/src/asyncSum.ts @@ -0,0 +1,21 @@ +/** + * 任務:實作一個函式 `asyncSum`,該函式應該能夠計算陣列中所有數字的總和。 + * 範例:asyncSum([1, 2, 3, 4, 5]) 應該回傳 15 + * @param numbers - 一個數字陣列 + * @returns - 回傳一個 Promise,該 Promise resolve 的值應該是陣列中所有數字的總和 + */ + + +export function asyncSum(numbers: number[]): Promise { + return new Promise((resolve, reject) => { + try { + const result = numbers.reduce((x, y ) => x + y, 0 ) + resolve(result) + } catch (error) { + reject(error); + } + }); +} + + +// 備註:題目中即使累加操作本身是同步的,也可以使用 Promise 來模擬非同步的情況。這可以讓學生練習如何使用 Promise 來處理非同步操作 \ No newline at end of file diff --git a/src/bookCategoryEnum.ts b/src/bookCategoryEnum.ts index fa2d6d6..be1bc33 100644 --- a/src/bookCategoryEnum.ts +++ b/src/bookCategoryEnum.ts @@ -23,6 +23,8 @@ export enum BookCategory { * 輸出: 'Book category: Novel' */ -export function getBookCategory(category) { +export function getBookCategory(category: BookCategory) { + let returntext: String = `Book category: ${category}`; // 在此實現函式 + return returntext; } \ No newline at end of file diff --git a/src/booleanChecker.ts b/src/booleanChecker.ts index b4bd530..e389701 100644 --- a/src/booleanChecker.ts +++ b/src/booleanChecker.ts @@ -2,9 +2,7 @@ * 判斷輸入的數字是否為正數 * @param number - 要判斷的數字 * - * 注意:這個函式目前有錯誤,需要修正。正確的實現應該是判斷輸入的數字是否大於 0。 */ export function isPositive(number: number): boolean { - // 故意寫錯的程式碼 - return number < 0; + return number > 0; } \ No newline at end of file diff --git a/src/calculator.ts b/src/calculator.ts index 1396ce2..6806b41 100644 --- a/src/calculator.ts +++ b/src/calculator.ts @@ -4,7 +4,7 @@ * @param b - 第二個數字 */ export function add(a: number, b: number): number { - // 在此實現函式 + return a + b; } /** @@ -13,7 +13,7 @@ export function add(a: number, b: number): number { * @param b - 第二個數字 */ export function subtract(a: number, b: number): number { - // 在此實現函式 + return a - b; } /** @@ -22,7 +22,7 @@ export function subtract(a: number, b: number): number { * @param b - 第二個數字 */ export function multiply(a: number, b: number): number { - // 在此實現函式 + return a * b; } /** @@ -30,8 +30,13 @@ export function multiply(a: number, b: number): number { * @param a - 第一個數字 * @param b - 第二個數字 */ -export function divide(a: number, b: number): number { - // 在此實現函式 +export function divide(a: number, b: number): number| null { + + if (b === 0) { + throw new Error('Cannot divide by zero'); + } + + return a / b; } /** diff --git a/src/dataProcessingModule.test.ts b/src/dataProcessingModule.test.ts new file mode 100644 index 0000000..9941b3e --- /dev/null +++ b/src/dataProcessingModule.test.ts @@ -0,0 +1,16 @@ +import { describe, it, expect } from 'vitest'; +import { sortArray, filterArray, transformArray } from './dataProcessingModule'; + +describe('資料處理模組', () => { + it('應該正確排序陣列', () => { + expect(sortArray([3, 1, 4])).toEqual([1, 3, 4]); + }); + + it('應該過濾陣列', () => { + expect(filterArray([1, 2, 3, 4], num => num % 2 === 0)).toEqual([2, 4]); + }); + + it('應該轉換陣列', () => { + expect(transformArray([1, 2, 3], num => num * 2)).toEqual([2, 4, 6]); + }); +}); \ No newline at end of file diff --git a/src/dataProcessingModule.ts b/src/dataProcessingModule.ts new file mode 100644 index 0000000..9f42039 --- /dev/null +++ b/src/dataProcessingModule.ts @@ -0,0 +1,40 @@ +/** + * 任務:實作一個函式 `sortArray`,將數字陣列由小到大排序。 + * + * 範例: + * sortArray([3, 1, 4]) 應該回傳 [1, 3, 4] + * + * @param numbers - 一個數字陣列 + * @returns - 回傳一個數字陣列,表示排序後的結果 + */ +export function sortArray(numbers: number[]): number[] { + return numbers.sort((x , y) => x - y); +} + +/** + * 任務:實作一個函式 `filterArray`,過濾數字陣列中符合條件的元素。 + * + * 範例: + * filterArray([1, 2, 3, 4], num => num % 2 === 0) 應該回傳 [2, 4] + * + * @param numbers - 一個數字陣列 + * @param predicate - 一個函式,用來判斷元素是否符合條件 + * @returns - 回傳一個數字陣列,表示過濾後的結果 + */ +export function filterArray(numbers: number[], predicate: (num: number) => boolean): number[] { + return numbers.filter((item) => predicate(item) ) +} + +/** + * 任務:實作一個函式 `transformArray`,將數字陣列中的每個元素進行轉換。 + * + * 範例: + * transformArray([1, 2, 3], num => num * 2) 應該回傳 [2, 4, 6] + * + * @param numbers - 一個數字陣列 + * @param transform - 一個函式,用來轉換元素 + * @returns - 回傳一個數字陣列,表示轉換後的結果 + */ +export function transformArray(numbers: number[], transform: (num: number) => number): number[] { + return numbers.map((item) => transform(item)); +} diff --git a/src/dataStore.test.ts b/src/dataStore.test.ts new file mode 100644 index 0000000..a73dace --- /dev/null +++ b/src/dataStore.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest'; +import { createDataStore } from './dataStore'; + +describe('DataStore 函式', () => { + it('應該允許添加和檢索項目', () => { + const store = createDataStore(); + store.add(1); + store.add(2); + expect(store.getAll()).toEqual([1, 2]); + }); + + it('應該能處理不同的類型', () => { + const stringStore = createDataStore(); + stringStore.add('hello'); + stringStore.add('world'); + expect(stringStore.getAll()).toEqual(['hello', 'world']); + }); +}); \ No newline at end of file diff --git a/src/dataStore.ts b/src/dataStore.ts new file mode 100644 index 0000000..d6193e8 --- /dev/null +++ b/src/dataStore.ts @@ -0,0 +1,32 @@ +/** + * 任務:實作一個函式 `createDataStore`,該函式會建立一個資料儲存庫,該儲存庫有兩個方法:add 和 getAll。 + * add 方法用於添加新的項目到儲存庫,getAll 方法用於獲取儲存庫中的所有資料。 + * + * 範例: + * const store = createDataStore(); + * store.add(1); + * store.add(2); + * store.getAll() 應該回傳 [1, 2] + * + * @returns - 回傳一個物件,該物件有 add 和 getAll 兩個方法 + */ +export function createDataStore() { + // 宣告一個名為 data 的變數,其為 T 型別的陣列,並初始化為空陣列 + // T 是一個泛型參數,代表任何型別 + let data: T[] = []; + + // 定義一個名為 add 的函式,該函式接收一個 T 型別的參數 item,並將 item 添加到 data 陣列中 + // 這裡的 T 也是泛型,所以 item 可以是任何型別 + function add(item: T){ + data.push(item); + } + + // 定義一個名為 getAll 的函式,該函式回傳 data 陣列的所有元素 + // 回傳的陣列中的元素型別也是 T,所以可以是任何型別 + function getAll(): T[]{ + return data + } + + + return { add, getAll }; +} \ No newline at end of file diff --git a/src/fetchData.test.ts b/src/fetchData.test.ts new file mode 100644 index 0000000..9fc8670 --- /dev/null +++ b/src/fetchData.test.ts @@ -0,0 +1,9 @@ +import { describe, it, expect } from 'vitest'; +import { fetchData } from './fetchData'; + +describe('非同步取得資料', () => { + it('應該能從提供的 URL 取得資料', async () => { + const data = await fetchData('https://jsonplaceholder.typicode.com/todos/1'); + expect(data).toHaveProperty('id'); + }); +}); \ No newline at end of file diff --git a/src/fetchData.ts b/src/fetchData.ts new file mode 100644 index 0000000..88ae221 --- /dev/null +++ b/src/fetchData.ts @@ -0,0 +1,26 @@ +/** + * 任務:實作一個 async 函式 `fetchData`,該函式應該能夠從指定的 URL 取得資料。 + * 範例:fetchData('https://jsonplaceholder.typicode.com/todos/1') 應該回傳一個包含 id、title 等屬性的物件 + * @param url - 要取得資料的 URL + * @returns - 回傳一個 Promise,該 Promise resolve 的值應該是從 URL 取得的資料 + */ + +// 請在下方寫下你的程式碼 + +type responseData = { + id: string; + title: String; +}; + +export async function fetchData(url: URL) { + return new Promise((resolve, reject) =>{ + try { + fetch(url).then((res) =>{ + const json = res.json() as unknown as responseData; + resolve(json); + }); + }catch (error){ + reject(error); + } + }) +} \ No newline at end of file diff --git a/src/filterByProperty.test.ts b/src/filterByProperty.test.ts new file mode 100644 index 0000000..c2e5142 --- /dev/null +++ b/src/filterByProperty.test.ts @@ -0,0 +1,17 @@ +import { describe, it, expect } from 'vitest'; +import { filterByProperty } from './filterByProperty'; + +describe('filterByProperty 函式', () => { + it('應該根據屬性值過濾物件陣列', () => { + const items = [ + { name: 'Alice', age: 30 }, + { name: 'Bob', age: 25 }, + { name: 'Carol', age: 30 } + ]; + const result = filterByProperty(items, 'age', 30); + expect(result).toEqual([ + { name: 'Alice', age: 30 }, + { name: 'Carol', age: 30 } + ]); + }); +}); \ No newline at end of file diff --git a/src/filterByProperty.ts b/src/filterByProperty.ts new file mode 100644 index 0000000..030e55c --- /dev/null +++ b/src/filterByProperty.ts @@ -0,0 +1,16 @@ +/** + * 任務:實作一個函式 `filterByProperty`,該函式應該過濾出陣列中的元素,其指定屬性的值等於給定值。 + * + * 範例: + * const array = [{ name: 'Alice', age: 20 }, { name: 'Bob', age: 20 }, { name: 'Charlie', age: 30 }]; + * filterByProperty(array, 'age', 20) 應該回傳 [{ name: 'Alice', age: 20 }, { name: 'Bob', age: 20 }] + * + * @param array - 一個物件的陣列 + * @param property - 要過濾的屬性名稱 + * @param value - 要過濾的屬性值 + * @returns - 回傳過濾後的陣列 + */ + +export function filterByProperty(array: T[], property: K, value: T[K]): T[] { + return array.filter((item) => item[property] === value); +} \ No newline at end of file diff --git a/src/inputHandler.ts b/src/inputHandler.ts index 52a6830..9d8ccde 100644 --- a/src/inputHandler.ts +++ b/src/inputHandler.ts @@ -11,6 +11,6 @@ * 輸出: 'Input is a number: 123' */ -export function handleInput(input) { - // 在此實現函式 +export function handleInput(input: number | string) { + return `Input is a ${typeof input}: ${input}` } \ No newline at end of file diff --git a/src/maxNumber.ts b/src/maxNumber.ts index f58c285..8d6c858 100644 --- a/src/maxNumber.ts +++ b/src/maxNumber.ts @@ -7,4 +7,5 @@ */ export function findMaxNumber(numbers: number[]): number { // 在此實現函式 + return Math.max(...numbers) } \ No newline at end of file diff --git a/src/multiArray.ts b/src/multiArray.ts index 4ac5f42..5288879 100644 --- a/src/multiArray.ts +++ b/src/multiArray.ts @@ -8,6 +8,6 @@ * 輸出: [[2, 4], [6, 8], [10, 12]] */ -export function processMultiArray(arr) { - // 在此實現函式 +export function processMultiArray(arr: number[][]): number[][] { + return arr.map((item) => [item[0] * 2, item[1] * 2]); } \ No newline at end of file diff --git a/src/numberSort.ts b/src/numberSort.ts index f002d57..2af7aae 100644 --- a/src/numberSort.ts +++ b/src/numberSort.ts @@ -9,5 +9,5 @@ */ export function sortNumbers(numbers: number[]): number[] { - // 在此實現函式 + return numbers.sort((a, b) => a - b) } \ No newline at end of file diff --git a/src/objectAccessor.test.js b/src/objectAccessor.test.js new file mode 100644 index 0000000..4eb7927 --- /dev/null +++ b/src/objectAccessor.test.js @@ -0,0 +1,12 @@ +import { describe, it, expect } from 'vitest'; +import { createObjectAccessor } from './objectAccessor'; + +describe('設定物件存取器', () => { + it('應該允許對任意物件的屬性進行讀寫操作', () => { + const obj = { name: 'Alice', age: 25 }; + const accessor = createObjectAccessor(obj); + expect(accessor.get('name')).toBe('Alice'); + accessor.set('age', 26); + expect(accessor.get('age')).toBe(26); + }); +}); \ No newline at end of file diff --git a/src/objectAccessor.ts b/src/objectAccessor.ts new file mode 100644 index 0000000..f087417 --- /dev/null +++ b/src/objectAccessor.ts @@ -0,0 +1,25 @@ +/** + * 任務:實作一個函式 `createObjectAccessor`,該函式接收一個物件,並回傳一個新的物件,該物件有兩個方法:get 和 set。 + * get 方法用於獲取原物件的屬性值,set 方法用於設定原物件的屬性值。 + * + * 範例: + * const obj = { name: 'John', age: 30 }; + * const accessor = createObjectAccessor(obj); + * accessor.get('name') 應該回傳 'John' + * accessor.set('age', 31); + * accessor.get('age') 應該回傳 31 + * + * @param obj - 一個物件 + * @returns - 回傳一個物件,該物件有 get 和 set 兩個方法 + */ +export function createObjectAccessor(obj: T) { + function get(key: K): T[K]{ + return obj[key] + } + + function set(key: K, value: T[K]){ + obj[key] = value; + } + + return {get, set}; +} \ No newline at end of file diff --git a/src/personalInfoModule.test.ts b/src/personalInfoModule.test.ts new file mode 100644 index 0000000..457f000 --- /dev/null +++ b/src/personalInfoModule.test.ts @@ -0,0 +1,9 @@ +import { describe, it, expect } from 'vitest'; +import { createPersonalInfo } from './personalInfoModule'; + +describe('個人資訊管理模組', () => { + it('應該創建個人資訊', () => { + const info = createPersonalInfo('John Doe', 30, 'john@example.com'); + expect(info).toEqual({ name: 'John Doe', age: 30, email: 'john@example.com' }); + }); +}); \ No newline at end of file diff --git a/src/personalInfoModule.ts b/src/personalInfoModule.ts new file mode 100644 index 0000000..018a4f5 --- /dev/null +++ b/src/personalInfoModule.ts @@ -0,0 +1,26 @@ +/** + * 任務:實作一個函式 `createPersonalInfo`,建立一個個人資訊的物件。 + * + * 範例: + * createPersonalInfo('John Doe', 30, 'john@example.com') 應該回傳 + * { + * name: 'John Doe', + * age: 30, + * email: 'john@example.com' + * } + * + * @param name - 一個字串,表示姓名 + * @param age - 一個數字,表示年齡 + * @param email - 一個字串,表示電子郵件地址 + * @returns - 回傳一個物件,包含 name、age 和 email 屬性 + */ + +export interface PersonalInfo { + name: string; + age: number; + email: string; +} + +export function createPersonalInfo(name: string, age: number, email: string): PersonalInfo { + return{ name, age, email,}; +} \ No newline at end of file diff --git a/src/shoppingCart.test.ts b/src/shoppingCart.test.ts new file mode 100644 index 0000000..4871381 --- /dev/null +++ b/src/shoppingCart.test.ts @@ -0,0 +1,22 @@ +import { describe, it, expect } from 'vitest'; +import { createShoppingCart } from './shoppingCart'; + +describe('購物車功能測試', () => { + it('應該可以加入商品並計算總價格', () => { + const cart = createShoppingCart(); + cart.addItem({ id: 'p1', name: '商品1', price: 100 }); + cart.addItem({ id: 'p2', name: '商品2', price: 200 }); + + expect(cart.getTotalPrice()).toBe(300); + expect(cart.getItemCount()).toBe(2); + }); + + it('清空購物車後,購物車內應該沒有商品', () => { + const cart = createShoppingCart(); + cart.addItem({ id: 'p1', name: '商品1', price: 100 }); + cart.clear(); + + expect(cart.getTotalPrice()).toBe(0); + expect(cart.getItemCount()).toBe(0); + }); +}); \ No newline at end of file diff --git a/src/shoppingCart.ts b/src/shoppingCart.ts new file mode 100644 index 0000000..f4b6099 --- /dev/null +++ b/src/shoppingCart.ts @@ -0,0 +1,41 @@ +interface Product { + id: string; + name: string; + price: number; +} + +/** + * 任務:實作一個函式 `createShoppingCart`,該函式應該能夠創建一個購物車。 + * 範例:createShoppingCart() 應該回傳一個購物車物件,該物件應該有 addItem、getTotalPrice、getItemCount 和 clear 等方法 + * @returns - 回傳一個購物車物件 + */ +export function createShoppingCart() { + let items: Product[] = []; + + function addItem(item: Product) { + items.push(item); + } + /** + * getTotalPrice 方法:計算購物車中所有商品的總價 + * @returns - 回傳購物車中所有商品的總價 + * 範例:getTotalPrice() 應該回傳 300,假設購物車中有兩個商品,價格分別為 100 和 200 + */ + function getTotalPrice() { + return items.reduce((x, y) => x+y.price, 0); + } + + function getItemCount() { + return items.length; + } + + function clear() { + items = []; + } + + return { + addItem, + getTotalPrice, + getItemCount, + clear + }; +} \ No newline at end of file diff --git a/src/stringProcessing.test.ts b/src/stringProcessing.test.ts new file mode 100644 index 0000000..1c6bfd9 --- /dev/null +++ b/src/stringProcessing.test.ts @@ -0,0 +1,8 @@ +import { describe, it, expect } from 'vitest'; +import { toUpperCase } from './stringProcessing'; + +describe('字串處理函式測試', () => { + it('應該將字串轉換為大寫', () => { + expect(toUpperCase('hello')).toBe('HELLO'); + }); +}); \ No newline at end of file diff --git a/src/stringProcessing.ts b/src/stringProcessing.ts new file mode 100644 index 0000000..6f72b0b --- /dev/null +++ b/src/stringProcessing.ts @@ -0,0 +1,13 @@ +/** + * 任務:實作一個函式 `toUpperCase`,將輸入的字串轉換為大寫。 + * + * 範例: + * toUpperCase("hello") 應該回傳 "HELLO" + * toUpperCase("world") 應該回傳 "WORLD" + * + * @param str - 一個需要被轉換為大寫的字串 + * @returns - 回傳轉換後的大寫字串 + */ +export function toUpperCase(str: string): string { + return str.toUpperCase(); +} \ No newline at end of file diff --git a/src/stringReverse.ts b/src/stringReverse.ts index bf755eb..35832ef 100644 --- a/src/stringReverse.ts +++ b/src/stringReverse.ts @@ -6,5 +6,5 @@ * 首先,使用 split 方法將字串轉換為字元陣列。然後,使用 reverse 方法將陣列反轉。最後,使用 join 方法將反轉後的陣列轉換回字串。 */ export function reverseString(str: string): string { - // 在此實現函式 + return str.split('').reverse().join(''); } \ No newline at end of file diff --git a/src/studentTuple.ts b/src/studentTuple.ts index de31b89..becb15e 100644 --- a/src/studentTuple.ts +++ b/src/studentTuple.ts @@ -7,6 +7,6 @@ * 輸出: 'Alice: 85%' */ -export function printStudentInfo(student) { - // 在此實現函式 +export function printStudentInfo(student: [string,number]): string { + return `${student[0]}: ${student[1]}%`; } \ No newline at end of file diff --git a/src/temperatureConverter.ts b/src/temperatureConverter.ts index e60ab42..b8c9296 100644 --- a/src/temperatureConverter.ts +++ b/src/temperatureConverter.ts @@ -4,4 +4,5 @@ * @returns 華氏溫度 */ export function celsiusToFahrenheit(celsius: number): number { + return (celsius * 9) / 5 + 32; } \ No newline at end of file diff --git a/src/todoInterface.ts b/src/todoInterface.ts index c3bec91..f7f60d0 100644 --- a/src/todoInterface.ts +++ b/src/todoInterface.ts @@ -13,7 +13,20 @@ * 輸出: [{ id: 1, task: 'Buy milk', completed: false }, { id: 2, task: 'Walk the dog', completed: false }] */ +interface Todo { + id: number; + task: string; + completed: boolean; +} + export function addTodo(todos: Todo[], task: string): Todo[] { - // 在此實現函式 + + const id = todos.length + 1; + const newTodo = { + id, + task, + completed: false, + } + return [...todos, newTodo]; } diff --git a/src/trafficLightEnum.ts b/src/trafficLightEnum.ts index 1e059f4..38643a4 100644 --- a/src/trafficLightEnum.ts +++ b/src/trafficLightEnum.ts @@ -8,8 +8,10 @@ * 輸出: 'The traffic light is Red' */ export enum TrafficLight { - + Red = 'Red', + Yellow = 'Yello', + Green = 'Green', } -export function getTrafficLightStatus(light) { - // 在此實現函式 +export function getTrafficLightStatus(light: TrafficLight) { + return `The traffic light is ${light}` } \ No newline at end of file diff --git a/src/uniqueElements.test.ts b/src/uniqueElements.test.ts new file mode 100644 index 0000000..b82309d --- /dev/null +++ b/src/uniqueElements.test.ts @@ -0,0 +1,8 @@ +import { describe, it, expect } from 'vitest'; +import { uniqueElements } from './uniqueElements'; + +describe('唯一元素函式', () => { + it('應從陣列中回傳唯一元素', () => { + expect(uniqueElements([1, 2, 2, 3, 4, 4, 4])).toEqual([1, 2, 3, 4]); + }); +}); \ No newline at end of file diff --git a/src/uniqueElements.ts b/src/uniqueElements.ts new file mode 100644 index 0000000..2781ed0 --- /dev/null +++ b/src/uniqueElements.ts @@ -0,0 +1,9 @@ +/** + * 任務:實作一個函式 `uniqueElements`,該函式應該從給定的數字陣列中找出所有的唯一元素,並回傳一個新的陣列。 + * 範例:uniqueElements([1, 2, 2, 3, 4, 4, 4]) 應該回傳 [1, 2, 3, 4] + * @param array - 一個數字陣列 + * @returns - 回傳包含所有唯一元素的新陣列 + */ +export function uniqueElements(array: number[]): number[] { + return Array.from(new Set(array)); +} \ No newline at end of file diff --git a/src/urlParsing.test.ts b/src/urlParsing.test.ts new file mode 100644 index 0000000..3539046 --- /dev/null +++ b/src/urlParsing.test.ts @@ -0,0 +1,14 @@ +import { describe, it, expect } from 'vitest'; +import { parseUrl } from './urlParsing'; + +describe('URL 解析函式測試', () => { + it('應正確解析 URL', () => { + const url = 'https://www.example.com/path'; + const result = parseUrl(url); + expect(result).toEqual({ + protocol: 'https:', + hostname: 'www.example.com', + path: '/path' + }); + }); +}); \ No newline at end of file diff --git a/src/urlParsing.ts b/src/urlParsing.ts new file mode 100644 index 0000000..75fc484 --- /dev/null +++ b/src/urlParsing.ts @@ -0,0 +1,28 @@ +/** + * 任務:實作一個函式 `parseUrl`,嘗試用 URL 方法,解析網址並 return 其組成部分。 + * + * 範例: + * parseUrl('https://www.example.com/path') 應該回傳 + * { + * protocol: 'https:', + * hostname: 'www.example.com', + * path: '/path' + * } + * + * @param url - 一個需要被解析的 URL + * @returns - 回傳一個物件,包含 protocol、hostname 和 path + */ +interface UrlParts { + protocol: string; + hostname: string; + path: string; +} + +export function parseUrl(url: string): UrlParts { + const link = new URL(url); + return{ + protocol: link.protocol, + hostname: link.hostname, + path: link.pathname, + } +} \ No newline at end of file diff --git a/src/userInfoExtension.test.ts b/src/userInfoExtension.test.ts new file mode 100644 index 0000000..057555e --- /dev/null +++ b/src/userInfoExtension.test.ts @@ -0,0 +1,9 @@ +import { describe, it, expect } from 'vitest'; +import { createFullUserInfo } from './userInfoExtension'; + +describe('使用者資訊擴充', () => { + it('應該正確合併使用者基本資訊和地址資訊', () => { + const user = createFullUserInfo({ name: 'John', age: 30, street: 'Main St', city: 'Metropolis' }); + expect(user).toEqual({ name: 'John', age: 30, street: 'Main St', city: 'Metropolis' }); + }); +}); \ No newline at end of file diff --git a/src/userInfoExtension.ts b/src/userInfoExtension.ts new file mode 100644 index 0000000..46806de --- /dev/null +++ b/src/userInfoExtension.ts @@ -0,0 +1,37 @@ +interface BasicUserInfo { + name: string; + age: number; +} + +interface AddressInfo { + street: string; + city: string; +} + +/** + * 任務:請實作一個 interface 或 type,藉此來建立 `FullUserInfo`,將 `BasicUserInfo` 和 `AddressInfo` 兩個介面的資訊合併。 + * + * 範例: + * FullUserInfo 應該包含以下屬性: + * name: string; + * age: number; + * street: string; + * city: string; + */ + +interface FullUserInfo extends BasicUserInfo, AddressInfo{} + + +/** + * 任務:實作一個函式 `createFullUserInfo`,將使用者的基本資訊和地址資訊合併成一個物件。 + * + * 範例: + * createFullUserInfo({ name: 'John', age: 30, street: 'Main St', city: 'Metropolis' }) + * 應該回傳 { name: 'John', age: 30, street: 'Main St', city: 'Metropolis' } + * + * @param user - 一個物件,包含使用者的基本資訊和地址資訊 + * @returns - 回傳一個物件,表示合併後的使用者資訊 + */ +export function createFullUserInfo(user: FullUserInfo): FullUserInfo { + return user; +} \ No newline at end of file diff --git a/src/userInterface.ts b/src/userInterface.ts index 4f06bda..ce81a8d 100644 --- a/src/userInterface.ts +++ b/src/userInterface.ts @@ -11,6 +11,12 @@ * 輸入: { firstName: 'John', lastName: 'Doe' } * 輸出: 'John Doe' */ -export function getFullName(user: /* 你的用戶介面 */): string { - // 在此實現函式 + +interface User{ + firstName: string; + lastName: string; +} + +export function getFullName(user: User): string { + return `${user.firstName} ${user.lastName}`; } \ No newline at end of file diff --git a/src/utilityFunctionsModule.test.ts b/src/utilityFunctionsModule.test.ts new file mode 100644 index 0000000..2dc5072 --- /dev/null +++ b/src/utilityFunctionsModule.test.ts @@ -0,0 +1,13 @@ +import { describe, it, expect } from 'vitest'; +import { formatDate, roundNumber } from './utilityFunctionsModule'; + +describe('公用函式模組', () => { + it('應該正確格式化日期', () => { + const date = new Date('2023-01-01'); + expect(formatDate(date)).toBe('2023-01-01'); + }); + + it('應該四捨五入數字', () => { + expect(roundNumber(1.5)).toBe(2); + }); +}); \ No newline at end of file diff --git a/src/utilityFunctionsModule.ts b/src/utilityFunctionsModule.ts new file mode 100644 index 0000000..f536f4e --- /dev/null +++ b/src/utilityFunctionsModule.ts @@ -0,0 +1,25 @@ +/** + * 任務:實作一個函式 `formatDate`,將日期物件轉換為 'YYYY-MM-DD' 的格式。 + * + * 範例: + * formatDate(new Date('2023-01-01')) 應該回傳 '2023-01-01' + * + * @param date - 一個日期物件 + * @returns - 回傳一個字串,表示格式化後的日期 + */ +export function formatDate(date: Date): string { + return new Date(date).toISOString().substring(0,10); +} + +/** + * 任務:實作一個函式 `roundNumber`,將數字四捨五入到最接近的整數。 + * + * 範例: + * roundNumber(1.5) 應該回傳 2 + * + * @param num - 一個數字 + * @returns - 回傳一個數字,表示四捨五入後的結果 + */ +export function roundNumber(num: number): number { + return Math.round(num); +} \ No newline at end of file diff --git a/src/vehicleInterface.ts b/src/vehicleInterface.ts index 54ef67c..9f9a53c 100644 --- a/src/vehicleInterface.ts +++ b/src/vehicleInterface.ts @@ -11,6 +11,13 @@ * 輸入: { brand: 'Toyota', model: 'Corolla', year: 2020 } * 輸出: 'Toyota Corolla (2020)' */ -export function vehicleInfo(vehicle: /* 你的車輛介面 */): string { - // 在此實現函式 + +interface Vehicle{ + brand: string; + model: string; + year: number; +} + +export function vehicleInfo(vehicle: Vehicle): string { + return `${vehicle.brand} ${vehicle.model} (${vehicle.year})` } \ No newline at end of file