-
Notifications
You must be signed in to change notification settings - Fork 0
javascript_in_depth_14
์ปค๋ง ํจํด์ ํจ์๋ฅผ ์ค๊ณํ ๋ ์ธ์ ์ ์ฒด๋ฅผ ๋๊ฒจ์ ํธ์ถํ ์๋ ์์ง๋ง, ์ผ๋ถ ์ธ์๋ ๋จผ์ ์ ๋ ฅํด๋๊ณ ๋๋จธ์ง๋ง ์ ๋ ฅ๋ฐ์ ์ ์๋๋ก ์๋ก์ด ํจ์๋ฅผ ๋ง๋๋ ํจํด์ ์๋ฏธํ๋ค. ํนํ, ์๋ฐ์คํฌ๋ฆฝํธ์์๋ ํด๋ก์ ๊ฐ ์์ด์ ๋จผ์ ์ผ๋ถ ์ ๋ ฅ๋ ๊ฐ์ ์ ์งํ๊ณ , ๊ฐ์ง๊ณ ์๋ ๊ฒ์ ์์ฃผ ์ฝ๊ฒ ๊ตฌํํ ์ ์๊ธฐ ๋๋ฌธ์ ์๋ฐ์คํฌ๋ฆฝํธ์์ ์ ์ฉํ๊ฒ ์ฌ์ฉํ ์ ์๋ ํจํด์ด๋ค.
์ปค๋ง ํจํด์ ์๋ฐ์คํฌ๋ฆฝํธ์ ์ธ์ด์ ์ธ ํน์ง ๋๋ฌธ์ ์์ฃผ ์ฝ๊ฒ ๊ตฌํํ ์ ์์ผ๋ฉฐ, ์ธ์๊ฐ ๋ง์ ๊ณตํต ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ ๋ ์ ์ฉํ๊ฒ ํ์ฉํ ์ ์๋ค๋ ์ฅ์ ์ด ์๋ค. ํ์ง๋ง ํด๋ก์ ๋ ๊ทธ๋ ์ง๋ง ํ๋ก๊ทธ๋จ์ด ๋์๊ฐ๋ ์์๋ฅผ ์ซ์๊ฐ๊ธฐ์๋ ์กฐ๊ธ ํ๋ค ์๋ ์๋ค๋ ๋จ์ ์ด ์์ผ๋ ๊ฐ๋ฐ ํจ์จ์ฑ๊ณผ ์์ค ๊ด๋ฆฌ์ ๋ํ ๊ท ํ์ ์ ๋ง์ถฐ์ผ ํ๋ค.
// ์ปค๋ง ํจํด์ ์ด์ฉํ ๋จ์ ๋ณํ
(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);
});
}());