首页 > web前端 > js教程 > 正文

设计模式 - JavaScript 挑战

DDD
发布: 2024-11-03 03:51:31
原创
504 人浏览过

Design Pattern - JavaScript Challenges

您可以在 repo Github 上找到这篇文章中的所有代码。


设计模式相关的挑战


事件发射器

class EventEmitter {
  constructor() {
    this._events = Object.create(null);
    this._key = 0;
  }

  on(eventName, listener) {
    if (!Object.hasOwn(this._events, eventName)) {
      this._events[eventName] = {};
    }

    const listenerId = this._key;
    this._key += 1;

    this._events[eventName][listenerId] = listener;

    return {
      off: () => {
        delete this._events[eventName][listenerId];
      }
    }
  }

  emit(eventName, ...args) {
    if (
      !Object.hasOwn(this._events, eventName) ||
      !Object.keys(this._events[eventName]).length
    ) {
      return false;
    }

    const listeners = { ...this._events[eventName] };
    Object.values(listeners).map((listener) => {
      listener.call(null, ...args);
    });

    return true;
  }

  once(eventName, listener) {
    const subscription = this.on(eventName, (...args) => {
      subscription.off();
      listener(...args);
    });

    return subscription;
  }
}

// Usage example
const emitter = new EventEmitter();

function addTwoNumbers(a, b) {
  console.log(`The sum is ${a + b}`);
}

const sub = emitter.on('foo', addTwoNumbers);
emitter.emit('foo', 1, 2);
// => "The sum is 3"

emitter.on('foo', (a, b) => {
  console.log(`The product is ${a * b}`);
});
emitter.emit('foo', 4, 5);
// > "The sum is 9"
// > "The product is 20"

sub.off();
emitter.emit('foo', -3, 9);
// > "The product is -27"
// (Only the multiply callback is triggered, the first one was unsubscribed.)

emitter.once('bar', (x) => {
  console.log(`Bar was called with ${x}`);
});

emitter.emit('bar', 1); // Logs: "Bar was called with 1"
emitter.emit('bar', 2); // Does nothing, the listener was already removed
登录后复制

方法链接

class Calculator {
  constructor(value) {
    this.result = value;
  }

  add(value) {
    this.result += value;
    return this;
  }

  subtract(value) {
    this.result -= value;
    return this;
  }

  multiply(value) {
    this.result *= value;
    return this;
  }

  divide(value) {
    if (value === 0) {
      throw new Error("Division by zero is not allowed");
    }
    this.result /= value;
    return this;
  }

  power(value) {
    this.result **= value;
    return this;
  }

  getResult() {
    return this.result;
  }
}

// Usage example
const calculator = new Calculator(10);
console.log(calculator.add(5).subtract(7).getResult()); // => 8

登录后复制

辛格尔顿

const globalMap = new Map();

export default {
  getInstance() {
    return globalMap;
  },
};
登录后复制

参考

  • 伟大的前端
  • 事件驱动编程 - Wikipedia.org
  • 16。创建一个事件发射器 - BFE.dev
  • 2694。事件发射器 - LeetCode
  • 2726。带方法链的计算器 - LeetCode
  • 方法链 - Wikipedia.org
  • 单例模式 - Wikipedia.org
  • 单例模式-patterns.dev

以上是设计模式 - JavaScript 挑战的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板