GithubHelp home page GithubHelp logo

Comments (2)

rjcnd105 avatar rjcnd105 commented on September 26, 2024 1

Rust Trait

https://doc.rust-lang.org/rust-by-example/trait.html 이것에 대한 개념 구현

trait은 공동으로 구현할 것을 추상화 해놓은 것.

해당 trait으로 지정한 프로퍼티는 오직 해당 trait만 알아야 하기 때문에 symbol로 내부적으로 생성하여 symbol로 지정하려는 구조체의 프로퍼티를 작성하려고 하였음.

이렇게 하면 해당 trait은 해당 구조체가 trait을 구현하였는지 알 수 있음.

간단하게 구현하는데는 성공했지만 실제로 사용하려니까 unique symbol 취급을 받지 못하여 해당 심볼로 프로퍼티를 선언할 수 없어서 실패함.

→ 적용하려면 nanoid(https://github.com/ai/nanoid) 같은걸로 해서 유니크한 아이디를 만들어서 해야겠음.

https://github.com/adobe/ferrum#traits 이것을 보고 ts 구현 방식을 참고함.

export class Trait<T extends Record<string, any>> {
  #keyToSym: = new Map<keyof T, symbol>()
  #symToTrait = new Map<symbol, any>()

  constructor(traitData: T) {
    for (const traitDataKey in traitData) {
      const sym = Symbol(traitDataKey)
      this.#keyToSym.set(traitDataKey, sym)
      this.#symToTrait.set(sym, traitData[traitDataKey])
    }
  }

  get syms() {
    return Object.fromEntries(this.#keyToSym) as { [key in keyof T]: symbol }
  }

  private get traits() {
    return Object.fromEntries(
      [...this.#keyToSym.entries()].map(([key, sym]) => [
        key,
        this.#symToTrait.get(sym),
      ])
    ) as { [key in keyof T]: T[key] }
  }

  static merge<T extends Trait<any>[]>(...traits: [...T]) {
    return new Trait({
      ...traits.reduce((obj, trait) => {
        return Object.assign(obj, { ...Object.entries(trait.traits) })
      }, {}),
    })
  }

  sym(name: keyof T): symbol {
    const _sym = this.#keyToSym.get(name)
    if (!_sym) throw Error('symbol not found.')

    return _sym
  }

  isImpl(t: any) {
    const obj = t.prototype?.constructor ? t.prototype : t

    return [...this.#keyToSym.values()].every((sym) => obj[sym])
  }
}

// 밑에는 걍 테스트 하던거...
const t = new Trait({
  name: 'ss',
}) /*?*/

t.sym('name') /*?*/
t.syms /*?*/

class A {}

t.isImpl(A) /*?*/

const s = Symbol()

class B {
  [t.sym('name')]: 'dd'; // ERROR!!
  [s]: 'aaa'
} /*?*/

from wednesday_salon.

rjcnd105 avatar rjcnd105 commented on September 26, 2024

참석
ts로 간략하게나마 trait 구현해보기

from wednesday_salon.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.