A Simple Explanation of Currying Functions(Javascript)

currying function’s usages, pros and cons

‘Currying’ has the same spelling as Curry that we love.

But ‘currying’ is derived from the name Haskell Brooks Curry who was known as a mathematician and a logician.

Currying is a technique that converting multiple arguments function into a single argument functions sequence.

Like this.

func(a, b, c) -> f(a)(b)(c)

Three arguments function is converted into three functions with single argument each.

f(a) returns value and (b) takes this value as a parameter. (c) also do the same thing. Get’s (b)‘s return value and return.

//non-curried
function plusFunc(a, b, c){
  console.log(a + b + c);
}

plusFunc(1, 2, 3);   // 6

//curried
function plusFunc(a){
    return function(b){
       return function(c){
          console.log(a + b + c);
       }
    }
}

plusFunc(1)(2)(4);  // 7

Then what are the differences between Curried and Non-curried?

non-curried : Function will be immediately executed even though parameters are not passed.
? Function definition : func(a, b, c)
? Function execution : func(a)
? Execution result : func(a, undefined, undefined)

curried : Execution will be suspended if parameters are not fully passed.
? Function definition : func(a, b, c)
? Function execution : func(a)
? Execution result : func(a) waits for b parameter.

So we can use currying as below.

function setAppell(appell){
    return function(name) {
       console.log(appell + name);   
    }
}

const setName = setAppell('Mr.');
setName('Right');  // Mr.Right
setAppell('Mr.')('Baker'); //Mr.Baker

//ES6 화살표 함수
const setAppell = appell => name => console.log(appell + name);

const setName = setAppell('Miss.');
setName('Dior');  // Miss.Dior

If we use currying function, we can also pass event and value together.

const setNumber = (num) => (event) => {
     console.log(event.target.id+':'+num);
}

<div onClick="setNumber(2)(event)" id='myNum'>
  click
</div>

// myNum:2

What is Pros.

? Pros
Reusable
– Reduced amount of code
– Readability

And Cons.

? Cons
Deeply nested functions cause memory and speed issue. So Currying

Mathematical Explanations of Currying



Most of the functions can be implemented without using currying. but you can expect a good effect if you use currying to improve productivity through reusability or readability.

Moment.js, A Simple Tool For Calculating Date And Time(feat.Nodejs)

Easy way to calculate date and time way better

Sometimes we need to calculate date and time.

Actually more than sometimes.

And this library, moment.js, is so powerful for your purpose.

Getting date, setting a date format whatsoever you want, subtracting date from date, counting days, and others.

Below listed some functions for your quick use.

Let’s dig it.


Install moment.js

Install library with below command.

npm install moment

Import the library with ‘require’ function.

var moment = require('moment');
moment();

//ES6 syntax
import moment from 'moment';
moment();

Let’s get started from parsing date.

const date = moment(""); //2022-01-23T11:15:00+09:00

We can display date using format() method with below tokens.

tokenmeanexample
YY(YY) year ex) YYYY -> 2022, YY -> 22
MM(MM) monthex) MMMM -> January, MM -> 01
DD dateex) DD -> 25
dd(dd) dayex) dd -> Tu, dddd -> Tuesday
hhhour(12)ex) hh -> 01
HH hour(24)ex) HH -> 13
mm minuteex) mm -> 07
sssecondex) ss -> 03
a am, pmex) a -> pm
Do ordinalex) Do -> 25th
//January Tu 2022, 01:07:21 pm
moment.format('MMMM dd YYYY, hh:mm:ss a'); 

//January Tuesday 2022, pm 01:17
moment.format('MMMM dddd YYYY, a hh:mm') 

// 01/25/2022
moment.format('MM/DD/YYYY'); 

isValid() method works well on it.

moment('2022-01-25','YYYY-MM-DD').isValid(); //true

moment('2022-02-30','YYYY-MM-DD').isValid(); //false

moment('My birth is 2022-1-25','YYYY-MM-DD').isValid(); //true

Also parsing every detail date is available by intuitive methods.

hour()get hour
minute()get minute
second()get second
millisecond()get millisecond
date()get date (1~31)
day()get day of week (0~6)
week()get week of year (1~53)
month()get month (0~11)
year()get year
moment(new Date).hour(); //13

moment().millisecond(); //331

moment().week(); //5

To get the difference in date, use diff() method.

const theDate = moment('2021-01-20', 'YYYY-MM-DD');
const myDate = moment('2022-01-25', 'YYYY-MM-DD');

myDate.diff(theDate, 'days');     // 5
myDate.diff(theDate, 'year');    // 1
myDate.diff(theDate, 'month');  // 12

We can use this method for counting expire date or calculate D-day.

And there is a bunch of methods this library thanks to the last long maintenance till today.

Please check official web for further infomation.

momentjs.com

AWS EC2 – From Launch New Instance To Install Everything We Need

Simple Explanation Of Setting up AWS EC2(Ubuntu18.04)

1. Launch New Instance In AWS

On a EC2 Management Console page, launch instances and choose Ubuntu Server 18.04 LTS with adequate instance type.

I chose t2 micro Type and launched.

On the next page, click Edit security groups and open port 22, 80, 443 for the next step.

Before launch the instance, you should select an existing key pair or create a new one.

If you don’t have any, create a new one and download key pair.

You should keep that key pair safe and don’t let be exposed to anyone.

We need an elastic IP address(Non-change address) for our accessibility.

Elastic IP lasts forever even if you stop the instance unless you release the IP address.

EC2 -> Network & Security -> Elastic IPs -> Allocate Elastic IP address.

Associate Elastic IP address and Choose an instance to stick them together.

Half way there.

Now you have your own instance and elastic IP address.

Keep going.

2. Connect To The Server Using SSH Client

You can use any SSH Client whatever you want.

This time I chose XShell7 that is free for Home/School.

Put the IP address in Host textbox.

Go to Authentication, write User Name ‘ubuntu’ and check Method Public Key.

Click Connect.

Browse and select the key pair that we downloaded.

If you get this message, now you are in.

3. Install Nodejs On Ubuntu Server

$ curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -

$ sudo apt-get install -y nodejs

Execute line by line and when it’s done, we can check by ‘node -v’ command.

If node version(v14.18.2 or something) is printed, installation is done.

4. Install MongoDB On Ubuntu Server

$ wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

If you see ‘OK‘ return with above command, you are ready for the next step.

$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

If you see ‘echo “deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list‘, move forward.

$ sudo apt-get update
$ sudo apt-get install -y mongodb-org

If you feel like something goes on a busy process, just wait.

When it’s done, check an installation with this command.

‘mongo -version’

Start mongodb service with this command.

$ sudo service mongod start

When successfully started, no message output.

$ mongo

> use admin

> db.createUser({ user:'id', pwd:'pwd', roles:[{"role":"userAdminAnyDatabase","db":"admin"},{"role":"readWriteAnyDatabase","db":"admin"}]})

exit

Have to change some codes for accessibility and security.

$ sudo vi /etc/mongod.conf

binIp : 127.0.0.1 -> bindIp: ::, 0.0.0.0

#security -> refer to above capture. no space before ‘enabled’ makes error.

save it!(‘wq’ command)

If you want to give a access try, use Compass with 27017 port opened.

5. Deploy(git clone)

Use Git, clone your project to your instance and install dependencies.

$ git clone https://github.com/id/repo

$ cd repo
$ npm install

6. Run Server With PM2

Install pm2 and run your own server.

pm2 makes your server keep running if you close the shell.

$ sudo npm install pm2 -g

$ sudo pm2 start index.js //in my case with arguement -> sudo pm2 start src/index.js --node-args="-r esm"

Now, your server won’t stop unless you stop the PM2.

You can check the PM2 status with below command.

$ sudo pm2 list

7. Install Nginx On Ubuntu Server

Nginx has additional functions that Nodejs do not have.

Simply in two ways, security and load balancing.

$ sudo apt-get install nginx

We opened port 80 for Nginx access.

When Nginx works, clients come in through Nginx door and Nginx leads them to internal port.

$ sudo service nginx start

When Nginx started, access it with your ip address.

Like http://3.34.65.190

Nginx welcomes you if you are on right process.

Now, Change some codes as below with vi editor to complete Nginx work.

$ cd /etc/nginx/sites-enabled

sudo vi default

Comment out try_files $uri $uri/ =404; and add

    proxy_pass http://yourIP:port/;
    proxy_set_header Host $http_host;
    proxy_http_version 1.1;
    proxy_set_header X-Nginx-Proxy true;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass takes clients to internal port that you set on Nodejs.

In my case, http://3.34.65.190:4000/;

Save it.

Next step is set a size limitation.

Nginx’s default file size setting is 1MB.

But if your page handles bigger than 1 MB files upload or download, this setting is necessary.

$ sudo vi /etc/nginx/nginx.conf
client_max_body_size 10M(limit size that you want);

Now, restart Nginx.

sudo service nginx restart

Now you can access you page that you made.

8. SSL certificate with Let’s Encrypt(http ->https)

Using Route53 service, get a own domain and manage DNS.

Redirect to your IP address and when you have your own domain, you can get a SSL certification with Let’s Encrypt for free.

$ sudo add-apt-repository ppa:certbot/certbot

$ sudo apt install python-certbot-nginx

$ sudo certbot --nginx -d yourdomain.com

Follow the direction, and then your web can get a SSL certification and https protocol is available.

The direction is simple.

1. enter your email address

2. Agree

3. Yes(or No)

4. choose No.2 (redirect http to https option)

And that’s it.

Important thing for the last step is opening the port 443.

Port 443 is a port for https.

Restart Nginx and access with your domain address.

Automatically https will welcome you.

Every 90 days, certification renewal is required and below is the command.

$ sudo certbot renew --dry-run

AWS : aws.amazon.com

CSS Combinators, make your CSS works easier (+,~, ,>)

Four combinators [Adjacent Sibling(+), General Sibling(~), Child(>), Descendant( )]

When set CSS Styles, below syntax is a basic.

h1 {
  color:#FFFF11;
  background: #000000;
}

.subTitle {
  font-size:13px;
  color:#FFFFFF;
  font-family:inherit;
}

#timeLine {
  background:gray;
}

But when you want to set Styles to a specific tag, using combinators is a smart selection.

combinators are mixed Styles. like ‘div + h1’ or ‘div > span’.

Any tags are mixable and there are four combinator types.

  • Adjacent Sibling (+)
  • General Sibling (~)
  • Child (>)
  • Descendant ( space )

1. Adjacent Sibling (+)

Adjacent Sibling uses + mark when specifies one element right after designated element.

h1 + p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm h1 tag</h1>
  <p>I'm orange</p>
  <h2>I'm h2 tag</h2>
  <p>I'm a second p tag</p>
  <h1>I'm h1 tag again</h1>
  <p>I'm orange too</p>
<div>

There are two conditions for adjacent sibling.

Element should share the same parent and second element has to come only if right after first element.

In the above HTML result, there are three <p> tag lines but only two lines are matched to the condition.

Therefore only two matched elements are working as mentioned.

2. General Sibling (~)

General Sibling uses ~ mark when specifies elements come after designated element.

h1 ~ p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm h1 tag</h1>
  <p>I'm orange</p>
  <h2>I'm h2 tag</h2>
  <p>I'm orange too</p>
<div>

There are two conditions for general sibling.

Element should share the same parent and second element has to come after first element.

In the above HTML result, every <p> tag after <h1>tag is working.

3. Child (>)

Use > marks when express child elements.

div > p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm just h1 tag</h1>
  <p> I'm colored orange</p>
  <span>
    <p>I'm not the one</p>
  </span>
  <p> I also am colored orange</p>
</div>

Second element has to be a direct child of first element.

In the above HTML result, only two direct child lines are working.

Fifth line is not working because its position is parent-child-child.

4. Descendant

Use space when express descendant elements.

div p {
  color:orange;
}

Result is shown below.

<div>
  <h1>I'm just h1 tag</h1>
  <p> I'm colored orange</p>
  <span>
    <p>Count me in</p>
  </span>
  <p> I also am colored orange</p>
</div>

As long as second element is a descendant of the first element, every matched line is working.


Combinators are easy and simple for efficient CSS work.

I hope this post is helpful to your CSS design.

개발자의 영어 사전(Developers’ terms in English)

Developers’ terms in English and Korean for foreign works

공부와 번역 일을 하면서 문장 번역과 업무에 핵심이 되는 개발 용어들을 틈틈이 정리하여 업데이트하는 포스트

  • anonymous function 익명 함수
  • arrow function 화살표 함수
  • ascending order 오름차순
  • assign 할당하다
  • braces { } 중괄호 (=curly brackets)
  • brackets [ ] 대괄호
  • boilerplate 상용구
  • cascade 연속, 종속
  • closure 클로저 (자바스크립트 클로저 포스팅)
  • curly brackets { } 중괄호 (=braces)
  • declarative programming 선언형 프로그래밍
  • deprecated 더 이상 사용되지 않는, 사라지게 될
  • descending order 내림차순
  • DOM (Document Object Model) 문서 객체 모델
  • duplicate 복사하다, 복제하다
  • execute 실행하다
  • first-class function 일등 함수 (함수와 변수를 구분하지 않는 함수)
  • function 함수
  • function call operator 함수 호출 연산자 ( )
  • functional programming 함수형 프로그래밍
  • global variable 전역변수
  • IIFE (Immediately Invoked Function Expression) 즉시 실행 함수
  • immutable 불변의
  • imperative programming 명령형 프로그래밍
  • impure function 불순 함수
  • inheritance 상속
  • invoke 호출하다
  • LOC(Lines of Code) 코드 라인
  • local variable 지역변수
  • loop 루프 / 반복 실행
  • manipulate 조작하다
  • memoization 메모이제이션(동일한 계산(또는 함수 생성) 반복 시 이전 계산 값을 메모리에 저장하여 반복 계산을 피함)
  • migration 이동, 이주
  • method 메서드
  • mutable 가변의
  • object 객체
  • object literal 객체 리터럴
  • object oriented programming (OOP) 객체 지향 프로그래밍
  • operand 피연산자
  • opinionated 의견이 있는, 고집이 있는, 방안을 제시하는, 제한을 두는(Angular 프레임워크 특징 설명 시 자주 사용)
  • parallel 병행의, 병렬의
  • parentheses ( ) 소괄호
  • parse 분석하다
  • pure fuction 순수 함수
  • quotation mark 따옴표
  • reactive programming 반응형 프로그래밍
  • recursive function 재귀 함수
  • regular expression 정규 표현
  • REST (REpresentational State Transfer) REST
  • response 응답, 리스폰스
  • request 요청, 리퀘스트
  • robust 탄탄한, 강력한
  • shallow copy 얕은 복사(동일한 객체를 참조)
  • snippet 조각, 단편, 코드 조각
  • syntax 문법
  • ternary operator 삼항연산자
  • UI (User Interface) UI
  • unopinionated 의견이 없는, 방안을 제시하지 않는, 제한을 두지 않는(Express 프레임워크 특징 설명 시 자주 사용)
  • variable 변수