JavaScript

๋ฐ˜๋ณต๋ฌธ ์—†์ด Array.prototype.filter()๋กœ ์‰ฝ๊ฒŒ ์žฌ๋ฐฐ์—ด ํ•˜๊ธฐ

๋‚จํฌ์ • 2023. 8. 15. 14:46

๐Ÿ“š Testing JavaScript Applications ๋ฅผ ๊ณต๋ถ€ํ•˜๋ฉด์„œ, ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์‹œ์Šคํ…œ์„ ์‚ฌ์šฉํ•˜๋ฉด์„œ ์„ ํƒ ์‚ญ์ œ, ์ „์ฒด ์‚ญ์ œ ๊ธฐ๋Šฅ์„ ๋งŒ๋“ค์–ด๋ณด์•˜๋‹ค.

๊ทธ ์ค‘ ์„ ํƒ ์‚ญ์ œ ๊ธฐ๋Šฅ์—์„œ, ์ฑ… ์˜ˆ์ œ์— ์žˆ๋Š” ๊ฒƒ์„ ๊ทธ๋Œ€๋กœ ๋ฐ›์•„๋“ค์ด๊ธฐ ๋ณด๋‹ค, ์ข€ ๋” ๋ชจ๋˜ํ•˜๊ฒŒ ๋ณด์—ฌ์ค„ ์ˆœ ์—†์„๊นŒ๋ฅผ ๊ณ ๋ฏผํ–ˆ๋‹ค.


์ฑ… ์˜ˆ์ œ ์ฝ”๋“œ

class Cart {
  constructor() {
    this.items = [];
  }
  addToCart(item) {
    this.items.push(item);
  }
  removeFromCart(item) {
    for (let i = 0; i < this.items.length; i++) {
      const currentItem = this.items[i];
      if (currentItem === item) {
        this.items.splice(i, 1);
      }
    }
  }
}

Array.prototype.splice()

์ฑ…์˜ ์˜ˆ์ œ๋ฅผ ๋ณด๋ฉด,

1. for ๋ฌธ์„ ํ†ตํ•ด ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ๋‹ด๊ธด ์•„์ดํ…œ ์ˆ˜ ๋งŒํผ `currentItem`์— ์ˆœ์„œ๋Œ€๋กœ ์žฌ๋ฐฐ์—ดํ•œ๋‹ค.

2. ๋งŒ์•ฝ ์žฌ๋ฐฐ์—ด ๊ณผ์ • ์ค‘์— removeFromCart()๋กœ ์„ ์–ธํ•œ ์•„์ดํ…œ์ด ๋ฐœ๊ฒฌ ๋  ๊ฒฝ์šฐ ํ•ด๋‹น ์ˆœ์„œ๋ฅผ ์ฐพ์•„ splice() ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ์‚ญ์ œํ•œ๋‹ค.

splice() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด์˜ ๊ธฐ์กด ์š”์†Œ๋ฅผ ์‚ญ์ œ ๋˜๋Š” ๊ต์ฒดํ•˜๊ฑฐ๋‚˜ ์ƒˆ ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ฐฐ์—ด์˜ ๋‚ด์šฉ์„ ๋ณ€๊ฒฝํ•œ๋‹ค.

 

// ๊ตฌ์กฐ
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
    
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

`for` ๋ฐ˜๋ณต๋ฌธ ์—†์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์žฌ๋ฐฐ์—ด ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์ง€ ์•Š์„๊นŒ ํ•ด์„œ ์ฐพ์•„๋ณด์•˜๋‹ค.

Array.prototype.filter()

filter() ๋ฉ”์„œ๋“œ๋Š” ์ฃผ์–ด์ง„ ํ•จ์ˆ˜์˜ ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผํ•˜๋Š” ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋ชจ์•„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

// ๊ตฌ์กฐ
arr.filter(callback(element[, index[, array]])[, thisArg])

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word) => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

 

์ตœ์ข… ์™„์„ฑ ์ฝ”๋“œ

class Cart {
  constructor() {
    this.items = [];
  }
  addToCart(item) {
    this.items.push(item);
  }
  removeFromCart(item) {
    this.items = this.items.filter((currentItems) => currentItems !== item);
  }
}

ํ›จ์”ฌ ๋ชจ๋˜ํ•œ ์ฝ”๋“œ..! ๐Ÿ˜Š ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ํ‘œํ˜„๊ณผ ํ•จ๊ป˜ ์“ธ ์ˆ˜ ์žˆ์–ด ์ข‹์€๋“ฏ.

์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ „์ฒด ์‚ญ์ œ์˜ ๊ฒฝ์šฐ์—” test code์™€ ํ•จ๊ป˜ ์˜ฌ๋ ค๋ณด๊ฒ ๋‹ค!