728x90

1. 비동기 처리

문제: 주어진 두 개의 비동기 함수 fetchData1과 fetchData2를 호출하여 그 결과를 배열로 반환하는 fetchAllData 함수를 작성하세요. 두 함수는 각각 1초 후에 값을 반환합니다.

 

function fetchData1() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('Data from fetchData1');
        }, 1000);
    });
}

function fetchData2() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('Data from fetchData2');
        }, 1000);
    });
}

async function fetchAllData() {
    // 여기에 코드를 작성하세요.
}

 

정답 

async function fetchAllData() {
    const results = await Promise.all([fetchData1(), fetchData2()]);
    return results;
}

 

2. 배열 및 객체조작

문제: 주어진 배열에서 중복된 값을 제거하고, 각 값의 출현 횟수를 객체 형태로 반환하는 countOccurrences 함수를 작성하세요.

function countOccurrences(arr) {
    // 여기에 코드를 작성하세요.
}

 

정답

function countOccurrences(arr) {
    return arr.reduce((acc, item) => {
        acc[item] = (acc[item] || 0) + 1;
        return acc;
    }, {});
}
728x90
728x90

php 에서도 가능하고 npm 으로도 설치가 가능해서 vue 나 react 에서도 가능한 스크립트다. 

 

상단에 아래와 같이 스크립트 url 을 추가해 주고 인쇄 되어야 하는 content 같은 div 아이디 값을 지정해 주고 .save 를 주면 pdf 로 다운로드가 가능하다. pdf 다운로드는 실제 변환되는 걸로 코딩을 하려면 무척 시간이 많이 걸리고 css 스타일도 inline 으로 밖아야 해서 코드도 무척 길어 지는데 아래와 같은 스크립트는 특정 div 만도 가능해서 좋은거 같다. 

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

 

pdf 다운로드 기능이 필요 하다면 참고해 보면 좋겠다.

var element = document.getElementById('content'); // PDF로 변환할 HTML 요소
html2pdf()
    .from(element)
    .save('document.pdf'); // 저장할 파일 이름

 

npm install html2pdf.js

 

728x90
728x90

다중으로 보내야 하는 경우 [] 괄호로 배열로 보내곤 하는데 이때 [] 괄호 안에 유니크한 번호를 넣으면 해당 번호를 기준으로 그룹 단위로 데이터를 테이블에 쌓을 수 있다. 요즘은 json 형태의 트리 구조로 데이터를 많이 잡기도 해서 조금 예스러운 코딩 일 수 있지만 종종 필요할 때가 있으니 참고하면 좋겠다. 

 

 

아래는 form 태그와 php 백 단에서 어떻게 처리되는지 에시를 보여준다.

<form method="POST" action="/your-endpoint">
    <table>
        <tr>
            <th>엘리베이터 여부</th>
            <td>
                <div class="com_chk__wrap">
                    <input type="hidden" name="cost_type[0]" value="189"> <!-- categories 189 : 엘리베이터여부 -->
                    <label><input type="radio" name="elevator_avail[0]" value="y">있음</label>
                    <label><input type="radio" name="elevator_avail[0]" value="n">없음 (있으나 사용 못 함)</label>
                </div>
            </td>
            <td class="td_center"><input type="number" name="labor_cost[0]" class="input num" value=""></td>
            <td class="td_center"><input type="number" name="margin_cost[0]" class="input num" value=""></td>
            <td class="td_center"><span class="">30,000원</span></td>
        </tr>
        <tr>
            <th>짐 여부</th>
            <td>
                <div class="com_chk__wrap">
                    <input type="hidden" name="cost_type[1]" value="188"> <!-- categories 188 : 짐 여부 -->
                    <label><input type="radio" name="luggage_avail[1]" value="y">있음</label>
                    <label><input type="radio" name="luggage_avail[1]" value="n">없음 (있으나 사용 못 함)</label>
                </div>
            </td>
            <td class="td_center"><input type="number" name="labor_cost[1]" class="input num" value=""></td>
            <td class="td_center"><input type="number" name="margin_cost[1]" class="input num" value=""></td>
            <td class="td_center"><span class="">30,000원</span></td>
        </tr>
        <!-- 추가적인 tr 요소들... -->
    </table>
    <button type="submit">제출</button>
</form>
<?php
// 데이터베이스 연결
$mysqli = new mysqli("localhost", "username", "password", "database");

// 연결 확인
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// POST 데이터 수신
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 각 항목 반복 처리
    foreach ($_POST['cost_type'] as $index => $costType) {
        // 엘리베이터 여부
        $availKey = 'elevator_avail[' . $index . ']';
        $laborCostKey = 'labor_cost[' . $index . ']';
        $marginCostKey = 'margin_cost[' . $index . ']';

        $avail = isset($_POST[$availKey]) ? $mysqli->real_escape_string($_POST[$availKey]) : '';
        $laborCost = isset($_POST[$laborCostKey]) ? (int)$_POST[$laborCostKey] : 0;
        $marginCost = isset($_POST[$marginCostKey]) ? (int)$_POST[$marginCostKey] : 0;
        $totalCost = $laborCost + $marginCost;

        // INSERT 쿼리 작성
        $query = "INSERT INTO estimate_extra_cost (est_number, cost_type, add_postion, title, title_code, etc1, labor_cost, margin_cost, total_cost) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        // 준비된 문을 사용하여 실행
        $stmt = $mysqli->prepare($query);

        // 필요한 값을 설정
        $estNumber = 'E001'; // 실제 사용하려는 값으로 변경
        $addPosition = 'etc'; // 필요에 따라 조정
        $title = ($costType == 189) ? '엘리베이터 여부' : '짐 여부'; // 조건에 따라 제목 설정
        $titleCode = ($costType == 189) ? 'CATEGORY_ELEVATOR' : 'CATEGORY_LUGGAGE'; // 카테고리 코드 설정

        // 문장에 파라미터 바인딩
        $stmt->bind_param("sssssiiiii", $estNumber, $costType, $addPosition, $title, $titleCode, $avail, $laborCost, $marginCost, $totalCost);
        $stmt->execute();
    }

    // 준비된 문 종료
    $stmt->close();
}

// 데이터베이스 연결 종료
$mysqli->close();
?>
728x90

+ Recent posts