Skip to content

javascript_in_depth_14

paul edited this page Apr 20, 2017 · 1 revision

๋””์ž์ธ ํŒจํ„ด ์‹ค์šฉ - ์ปค๋ง ํŒจํ„ด

์ปค๋ง ํŒจํ„ด์€ ํ•จ์ˆ˜๋ฅผ ์„ค๊ณ„ํ•  ๋–„ ์ธ์ž ์ „์ฒด๋ฅผ ๋„˜๊ฒจ์„œ ํ˜ธ์ถœํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ, ์ผ๋ถ€ ์ธ์ž๋Š” ๋จผ์ € ์ž…๋ ฅํ•ด๋‘๊ณ  ๋‚˜๋จธ์ง€๋งŒ ์ž…๋ ฅ๋ฐ›์„ ์ˆ˜ ์žˆ๋„๋ก ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ๋Š” ํŒจํ„ด์„ ์˜๋ฏธํ•œ๋‹ค. ํŠนํžˆ, ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ํด๋กœ์ €๊ฐ€ ์žˆ์–ด์„œ ๋จผ์ € ์ผ๋ถ€ ์ž…๋ ฅ๋œ ๊ฐ’์„ ์œ ์ง€ํ•˜๊ณ , ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฒƒ์„ ์•„์ฃผ ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํŒจํ„ด์ด๋‹ค.

ํ™œ์šฉ

์ปค๋ง ํŒจํ„ด์€ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ์–ธ์–ด์ ์ธ ํŠน์ง• ๋•Œ๋ฌธ์— ์•„์ฃผ ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ธ์ž๊ฐ€ ๋งŽ์€ ๊ณตํ†ต ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์œ ์šฉํ•˜๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ํด๋กœ์ €๋„ ๊ทธ๋ ‡์ง€๋งŒ ํ”„๋กœ๊ทธ๋žจ์ด ๋Œ์•„๊ฐ€๋Š” ์ˆœ์„œ๋ฅผ ์ซ’์•„๊ฐ€๊ธฐ์—๋Š” ์กฐ๊ธˆ ํž˜๋“ค ์ˆ˜๋„ ์žˆ๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ์œผ๋‹ˆ ๊ฐœ๋ฐœ ํšจ์œจ์„ฑ๊ณผ ์†Œ์Šค ๊ด€๋ฆฌ์— ๋Œ€ํ•œ ๊ท ํ˜•์„ ์ž˜ ๋งž์ถฐ์•ผ ํ•œ๋‹ค.

์˜ˆ์ œ

// ์ปค๋ง ํŒจํ„ด์„ ์ด์šฉํ•œ ๋‹จ์œ„ ๋ณ€ํ™˜
(function () {
    Function.prototype.curry = function() {
        if (arguments.length<1) {
            return this;
        }
        var _this = this,
            args = Array.prototype.slice.apply(arguments);
        return function() {
            return _this.apply(this, args.concat(Array.prototype.slice.apply(arguments)));
        }
    }

    function unitConvert(fromUnit, toUnit, factor, input) {
        return `${input} ${fromUnit} === ${(input*factor).toFixed(2)} ${toUnit}`;
    }

    var cm2inch = unitConvert.curry('cm', 'inch', 0.393701),
        metersquare2pyoung = unitConvert.curry('m^2', 'pyoung', 0.3025),
        kg2lb = unitConvert.curry('kg', 'lb', 2.204623),
        kmph2mph = unitConvert.curry('km/h', 'mph', 0.621371);

    console.log(cm2inch(10));
    console.log(metersquare2pyoung(30));
    console.log(kg2lb(50));
    console.log(kmph2mph(100));
}());
// XMLHttpRequest๋ฅผ ์œ„ํ•œ ์ปค๋ง ํŒจํ„ด
(function () {
    Function.prototype.curry = function() {
        if (arguments.length<1) {
            return this;
        }
        var _this = this,
            args = Array.prototype.slice.apply(arguments);
        return function() {
            return _this.apply(this, args.concat(Array.prototype.slice.apply(arguments)));
        }
    }

    function ajax(method, url, data, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = function () {
            if (xhr.status === 200) {
                callback.call(this, xhr.responseText);
            }
        }
        xhr.send(data);
    }

    var ajaxGet = ajax.curry("GET"),
        ajaxPost = ajax.curry("POST"),
        ajaxPut = ajax.curry("PUT"),
        ajaxDelete = ajax.curry("DELETE");

    ajaxGet("/data", null, function (responseText) {
        console.log(responseText);
    });
}());

Clone this wiki locally