import "./app.css";
const StockForm = (addStock) => {
const stockForm = document.querySelector("#stock-form");
stockForm.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(stockForm)
const [stockName, buyPrice, stockAmount, currentPrice] = [
formData.get('stock-name'),
Number(formData.get('buy-price')),
Number(formData.get('stock-amount')),
Number(formData.get('current-price'))
]
// stockForm으로부터 정보를 얻어, addStock에 데이터를 넘겨주세요.
addStock(stockName, buyPrice, stockAmount, currentPrice);
stockForm.reset();
});
};
const StockTable = (stocks) => {
const stockTable = document.querySelector(".stock-table");
const tableBody = stockTable.querySelector(".stock-table-body");
const tableData = stocks.map(({stockName,buyPrice,currentPrice,stockAmount})=>({
name:stockName,
earningRate:((currentPrice-buyPrice) / buyPrice * 100).toFixed(2),
porfit:(currentPrice - buyPrice) * stockAmount
})
)
// stocks 데이터를 이용해, tbody 안에 들어갈 태그를 동적으로 만드세요.
tableBody.innerHTML = tableData.map(({name,earningRate,porfit})=>
`
<tr>
<td>${name}</td>
<td>${earningRate}</td>
<td>${porfit}</td>
</tr>
`)
};
const StockResult = (stocks) => {
const resultTextElement = document.querySelector(".result-text");
if (stocks.length === 0) {
resultTextElement.innerText = "종목을\n추가하세요.";
return;
}
const [buyPriceSum, currentPriceSum] = [
stocks.reduce((acc, cur) =>acc+cur.buyPrice * cur.stockAmount, 0),
stocks.reduce((acc, cur) =>acc+cur.currentPrice * cur.stockAmount, 0)
]
const earningRate = ((currentPriceSum - buyPriceSum) / buyPriceSum * 100).toFixed(2)
const profit = Math.floor(currentPriceSum - buyPriceSum)
// 총 수익률과 총 수익금을 계산하여, resultText를 채워주세요.
resultTextElement.innerText = `현재 총 수익률은 ${earningRate}%이며,\n총 수익금은 ${profit}원 입니다.`;
};
const App = () => {
const stocks = [
// 테스트 데이터
// {
// stockName: "삼성전자",
// buyPrice: 80000,
// stockAmount: 8,
// currentPrice: 82000,
// },
// {
// stockName: "SK하이닉스",
// buyPrice: 100000,
// stockAmount: 12,
// currentPrice: 104000,
// },
// {
// stockName: "엘리스",
// buyPrice: 10000,
// stockAmount: 120,
// currentPrice: 11000,
// },
];
// StockTable, StockResult 렌더링 결과를, stock 정보를 바탕으로 계산합니다.
const render = () => {
StockTable(stocks);
StockResult(stocks);
};
const addStock = (stockName, buyPrice, stockAmount, currentPrice) => {
stocks.push({ stockName, buyPrice, stockAmount, currentPrice });
render();
};
StockForm(addStock);
render();
};
module.exports = App;
위는 공부용 코드
아래는 챗gpt 용 간결 정리 공부용
// 필요한 스타일시트를 가져옵니다.
import "./app.css";
// 주식 관련 데이터 입력 폼 컴포넌트입니다.
const StockForm = (addStock) => {
// stock-form 요소를 가져옵니다.
const stockForm = document.querySelector("#stock-form");
// 폼이 제출될 때 이벤트를 처리합니다.
stockForm.addEventListener("submit", (e) => {
e.preventDefault(); // 기본 제출 동작 방지
// 폼 데이터를 가져와서 필요한 데이터를 추출합니다.
const formData = new FormData(stockForm);
const { 'stock-name': stockName, 'buy-price': buyPrice, 'stock-amount': stockAmount, 'current-price': currentPrice } = Object.fromEntries(formData);
// 추출된 데이터를 addStock 함수에 전달하여 주식을 추가합니다.
addStock(stockName, Number(buyPrice), Number(stockAmount), Number(currentPrice));
stockForm.reset(); // 입력 폼을 초기화합니다.
});
};
// 주식 데이터를 표시하는 테이블 컴포넌트입니다.
const StockTable = (stocks) => {
// 테이블과 테이블 본문 요소를 가져옵니다.
const stockTable = document.querySelector(".stock-table");
const tableBody = stockTable.querySelector(".stock-table-body");
// stocks 데이터를 가공하여 HTML 테이블로 동적으로 렌더링합니다.
const tableData = stocks.map(({ stockName, buyPrice, currentPrice, stockAmount }) => ({
name: stockName,
earningRate: ((currentPrice - buyPrice) / buyPrice * 100).toFixed(2),
profit: (currentPrice - buyPrice) * stockAmount,
}));
// tableData를 HTML 문자열로 변환하여 테이블 본문에 설정합니다.
tableBody.innerHTML = tableData.map(({ name, earningRate, profit }) => `
<tr>
<td>${name}</td>
<td>${earningRate}</td>
<td>${profit}</td>
</tr>
`).join('');
};
// 주식 데이터의 총 수익과 수익률을 표시하는 컴포넌트입니다.
const StockResult = (stocks) => {
// 결과 텍스트 요소를 가져옵니다.
const resultTextElement = document.querySelector(".result-text");
// 주식 데이터가 없을 경우 "종목을 추가하세요." 메시지를 표시합니다.
if (stocks.length === 0) {
resultTextElement.innerText = "종목을\n추가하세요.";
return;
}
// 주식 데이터를 이용하여 총 수익과 수익률을 계산합니다.
const buyPriceSum = stocks.reduce((acc, cur) => acc + cur.buyPrice * cur.stockAmount, 0);
const currentPriceSum = stocks.reduce((acc, cur) => acc + cur.currentPrice * cur.stockAmount, 0);
const earningRate = ((currentPriceSum - buyPriceSum) / buyPriceSum * 100).toFixed(2);
const profit = Math.floor(currentPriceSum - buyPriceSum);
// 결과 텍스트를 설정하여 화면에 표시합니다.
resultTextElement.innerText = `현재 총 수익률은 ${earningRate}%이며,\n총 수익금은 ${profit}원 입니다.`;
};
// 앱의 메인 컴포넌트입니다.
const App = () => {
const stocks = []; // 주식 데이터를 저장하는 배열
// 화면을 렌더링하는 함수
const render = () => {
StockTable(stocks); // 주식 데이터를 표시하는 테이블 렌더링
StockResult(stocks); // 주식 데이터의 총 수익과 수익률을 표시하는 컴포넌트 렌더링
};
// 주식 추가 함수
const addStock = (stockName, buyPrice, stockAmount, currentPrice) => {
// 주식 데이터를 배열에 추가
stocks.push({ stockName, buyPrice, stockAmount, currentPrice });
render(); // 화면을 다시 렌더링하여 업데이트된 주식을 표시
};
StockForm(addStock); // 주식 입력 폼 컴포넌트 초기화
render(); // 초기 화면 렌더링
};
// 앱 컴포넌트를 내보냅니다.
export default App;