반응형
  • 람다함수를 사용하면 코드가 간결해진다
  • 메모리 사용이 효율적이다.
# 람다함수 선언 방법
lambda a : a-1

# 호출방법 1 : 그대로 호출
print ((lambda a:a-1)(10))

# 호출방법 2 : 변수에 담아서 호출
minus_ten = lambda a : a-10
print (minus_ten(100))

# 람다함수 if 문 사용
def is_positive_num(a):
  if a > 0:
    return True
  else:
    return False

lambda a : True if a > 0 else False

개인적으로 함수 자체를 호출하는 방법보다는 변수에 담아서 호출하는게 가독성에는 더 좋아보인다.

 

728x90
반응형

'Development > Python' 카테고리의 다른 글

파이썬 문법 : class 속성들  (0) 2023.03.02
파이썬 문법 : map, filter 함수  (0) 2023.02.28
파이썬 문법 : 키워드 가변 매개변수 kwargs  (0) 2023.02.27
파이썬 문법 : 튜플  (0) 2023.02.27
Python 가상환경  (0) 2022.10.27
반응형
  • kwargs 는 keyword arguments
  • 매개변수 앞에 ** 가 붙는다
  • 딕셔너리 로 인식한다.
def comment_info(**kwargs):
  print(kwargs)
  for key,value in kwargs.items():
    print(f'{key}:{value}')

comment_info(name='test1', age=10)

output
{'name': 'test1', 'age': 10}
name:test1
age:10

추가 사항 : 추가적으로 *args 는 임의의 개수의 argument 를 의미한다. kwargs 와는 달리 tuple 로 인식한다.

728x90
반응형

'Development > Python' 카테고리의 다른 글

파이썬 문법 : map, filter 함수  (0) 2023.02.28
파이썬 문법 : 람다 함수  (0) 2023.02.27
파이썬 문법 : 튜플  (0) 2023.02.27
Python 가상환경  (0) 2022.10.27
Ubuntu 에서 파이썬 버전 확인 및 변경  (0) 2022.10.25
반응형
  • 튜플은 () 로 정의된다
  • 튜플은 값을 바꿀수 없다.
t1 = ()
t2 = (1,)
t3 = (1,2,3)
t4 = 1,2,3
t5 = ('a', 'b', ('ab', 'cd'))
  • 1개의 요소만 가질때에는 콤마(,) 를 붙여야 한다.
  • 괄호가 생략 가능하다
  • 개수가 정해지지 않은 매개 변수로 사용된다. (* 가 매개변수 앞에 붙는다.) = 위치가변 매개변수
def print_fruits(*args):
  print(args)
  for arg in args:
    print(arg)

print_fruits('apple', 'banana', 'melon')

output
('apple', 'banana', 'melon')
apple
banana
melon

 

728x90
반응형
반응형

Union : 값이 허용된 타입을 두개 이상의 가능한 타입으로 확장하는 것

let physicist = Math.random() > 0.5 ? "TEST" : 100;

실제 위와 같은 코드에서는 아래와 같이 판단한다.

Narrowing : 값이 허용된 타입이 하나 이상의 가능한 타입이 되지 않도록 좁히는것

let animal: number | string;
animal = 'tiger';

number 와 string 으로 선언했지만 값 할당을 통해서 string 타입으로 확인되었기 때문에 string 관련 메소드만 사용 가능 하다.

아래와 같이 조건문을 통해서도 타입이 결정될수 있다.

let physicist = Math.random() > 0.5 ? "TEST" : 100;

typeof physicist === "string" ? physicist.toUpperCase() : physicist.toFixed();

 

728x90
반응형
반응형

개요

  • 네트워크
    • IPV4
      • 첫번째 옥텟의 앞자리 숫자를 가지고 구분
      • 호스트 비트 수는 1개의 네트워크 안에 있는 IP 수를 의미한다.
      • A Class
        • 맨 첫번째 앞자리 비트가 0
        • 네트워크 비트 2^7
        • 호스트비트 2^24
      • B Class
        • 맨 첫번째 앞자리 비트가 10
        • 네트워크 비트 2^14
        • 호스트 비트 2^16
      • C Class
        • 맨 첫번째 앞자리 비트가 110
        • 네트워크 비트 2^21
        • 호스트 비트 2^8
  • Route Table
    • 트래픽이 어디로 가야 할지 알려주는 테이블
  • 구성
    • IGW - Router - Route Table - NACL - VPC Subnet
  • NACL
    • NACL - stateless
    • Security Group - stateful
728x90
반응형
반응형

html 태그로 표현되어있는 문법을 createElement 로 변환해준다.

const vdom = <p>
  <h1>헤더</h1>
  <ul>
    <li style="color:red">첫번째</li>
    <li style="color:blue">두번째</li>
  </ul>
</p>

위에 있는 코드가 아래와 같이 변환이 된다.

"use strict";

const vdom = /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement("h1", null, "\uD5E4\uB354"), /*#__PURE__*/React.createElement("ul", null, /*#__PURE__*/React.createElement("li", {
  style: "color:red"
}, "\uCCAB\uBC88\uC9F8"), /*#__PURE__*/React.createElement("li", {
  style: "color:blue"
}, "\uB450\uBC88\uC9F8")));

출처 : https://babeljs.io/ 에서 변환함.

왜 저렇게 변환이 필요한가?? 

// app.js
const vdom = createElement(
  "p",
  {},
  createElement("h1", {}, "헤더"),
  createElement(
    "ul",
    {},
    createElement("li", { style: "color:red" }, "첫번째"),
    createElement("li", { style: "color:blue" }, "두번째")    
  )
);

// react.js
export function createElement(tag, props, ...children) {
  props = props || {}
  return {
    tag,
    props,
    children,
  };
}

JSX 를 사용하지 않으면 위와같이 코드를 작성해줘야 한다. 하지만 위보다는 html 태그 구조가 눈에 더 잘 들어온다.

한가지 더 기본적으로 JSX 가 변환을 할때에 메소드를 보면 React.createElement를 사용한다. 하지만 위에 작성된 코드에서는 createElement를 사용하고 있다. 이걸 변경해주려면 다음과 같이 표시해 주면된다. 변환된 코드는 아래와 같다.

/* @jsx createElement */
// app.js
const vdom = createElement(
  "p",
  {},
  createElement("h1", {}, "헤더"),
  createElement(
    "ul",
    {},
    createElement("li", { style: "color:red" }, "첫번째"),
    createElement("li", { style: "color:blue" }, "두번째")    
  )
);

실제로 babel 사이트에서 변환된 것을 봐도 변경된 것을 알수 있다.

"use strict";

// app.js
const vdom = createElement("p", {}, createElement("h1", {}, "헤더"), createElement("ul", {}, createElement("li", {
  style: "color:red"
}, "첫번째"), createElement("li", {
  style: "color:blue"
}, "두번째")));

 

728x90
반응형
반응형

개요

  • node.js 문법을 써야 한다.
  • entry 에 있는 명령어를 읽어서 변환과정을 거쳐서 output 으로 전달함.
  • entry -> module -> plugin -> output 으로 전달됨
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");

module.exports = {
  mode: "development",
  entry: "./src/app.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  devServer: {
    compress: true,
    port: 9999,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"]
          },
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "2.3 setup webpack & babel",
      template: "index.html"
    }),
  ],
};
  • loader
    • 특정 모듈을 변환하는대 사용한다.
    • .js 파일을 babel-loader 를 사용해서 변환해라. /node_modules/ 폴더는 제외하고!!
  • plugin
    • 플러그인을 사용하면 번들을 최적화 하거나 애셋을 관리하고 환경변수등을 주입하는게 가능하다.
    • require 를 통해서 플러그인을 요청한다.
    • 다른 목적을 위해 플러그인을 여러번 사용할수 있기 때문에 new 를 사용해서 인스턴스를 만들어야 한다.

참고

https://webpack.kr/concepts/

728x90
반응형
반응형

여러가지 배열 연산 형태 
함수 형태나 쓰임이 많다보니 코드를 봤을때 대체 무슨 의미인지 파악이 어려워서 공부하다가 형태를 기억하면 좋을것 같아서 남겨놔봤다. 

type Book = {
    title: string;
    copyright?: string;
    author?: string;
};

const books: string[] = [
    "헨리 6세",
    "리처드 3세",
    "실수 연발",
    "말괄량이 길들이기",
    "헨리 8세",
];

// foreach 문
books.forEach((book: string, idx: number, books: string[]) => {
    console.log(book, idx);
})

// map 사용1
const bookObject: Book[] = books.map((book:string) =>{
    return {
        title:book,
        author: undefined,
    };
});

console.log(bookObject); 
/*  [ { author: undefined, title: '헨리 6세' },
  { author: undefined, title: '리처드 3세' },
  { author: undefined, title: '실수 연발' },
  { author: undefined, title: '말괄량이 길들이기' },
  { author: undefined, title: '헨리 8세' } ] */

// map 사용2
const ShakespeareOneBooks: Book[] = books.map((book: string) => ({
    title:book
}))
.map((book: Book) => ({
    ...book,
    author: "William Shakespeare"
}));

console.log(ShakespeareOneBooks);

// map 사용2 와 형태가 다르지만 동일 동작임.
const bookTitleToBookObject = (book: string) => ({title:book});
const makeAuthor = (name: string) => (book: Book) => ({
    ...book,
    author: name
});

const shakespeareTwoBooks: Book[] = books
.map(bookTitleToBookObject)
.map(makeAuthor("William Shakespeare"));

console.log(shakespeareTwoBooks);

// filter
const henry: Book[] = shakespeareTwoBooks.filter((book: Book) =>
    book.title.includes("헨리")
);

console.log(henry);

// reduce
// reduce 는 함수와 초기화 값을 넘겨줌
// 함수에는 2개의 인자를 넘겨주는데 첫번째에는 초기값, 두번째는 배열의 값을 넘겨줌
// 함수가 반복되면서 첫번째 인자에는 다시 결과값을 계속 넣어주게됨.
// 0, 10 -> 10, 5 -> 15, 3 .. 이런 형태로 값이 들어감.
const someNumbers: number[] = [10,5,3,14,56];
const someNumber = someNumbers.reduce((a:number, b:number) => a + b , 0)

console.log(someNumber);	// 88

type SomeObject = {
    [key: string]: string | number;
};

// reduce object
const someObjects: SomeObject[] = [
    { border: "none"},
    { fontSize: 24},
    {className: "box sm-box"},
];

const someObject: SomeObject = someObjects.reduce(
    (a: SomeObject, b: SomeObject) => ({...a, ...b}),
    {}
);
console.log(someObject) // { border: 'none', className: 'box sm-box', fontSize: 24}

(출처 : 패스트 캠퍼스 - 김민태의 프론트엔드 아카데미 : https://fastcampus.co.kr/dev_academy_kmt1)

728x90
반응형
반응형

매일 봐도 까먹는 자바스크립트 함수형태들...

function fn(x){
	return x + 100;
}

const result = fn(10);

# 이름없는 함수
const fn2 = function (){
	return 100;
};

fn2();

# 즉시 실행 함수
(function(){
	console.log('test')
})();

# Arrow 함수
const fn3 = () => {
	return 100;
}

const fn4 = () => 100;

# Generator 함수
# 최초 호출하면 함수가 실행되지 않고 실행 준비상태로 만듬. 
# 그리고 객체를 반환하며 이 객체에는 함수를 실행할 도구가 담겨져 있다.
# 도구를 이용해서 함수를 실행하고 멈추고 할수 있음.
function* fn5(){
	yield 10; 
	yield 20;
	return 30;
}

const g = fn5();
g.next();  // {value: 10, done: false}
g.next();  // {value: 20, done: false}
g.next();  // {value: 30, done: true}


# 비동기 함수
async function fn6(){
    
}

 

 

728x90
반응형

+ Recent posts