【每日学习3.27】01背包/发布订阅模式/深入版手写bind

文章介绍了如何使用JavaScript实现经典01背包问题的动态规划解法,展示了简易的发布订阅模式类`EventHub`,以及对Function.prototype.bind的模拟实现。通过示例代码,读者可以理解这三个概念在实际编程中的应用。
摘要由CSDN通过智能技术生成

3.27

  • 经典01背包
function solve (n, V, vw) {
  let dp = new Array(n + 1).fill(0).map(() => new Array(V).fill(0))
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= V; j++) {
      if (j < vw[i - 1][0]) {
        dp[i][j] = dp[i - 1][j]
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - vw[i - 1][0]] + vw[i - 1][1])
      }
    }
  }
  return dp[n][V]
}
  • 手写简易发布订阅模式
class EventHub {
  map = {}
  on (name, fn) {
    this.map[name] = this.map[name] || []
    this.map[name].push(fn)
  }
  off (name, fn) {
    this.map[name] = this.map[name] || []
    let index = this.map[name].indexOf(fn)
    if (index < 0) return
    this.map[name].splice(index, 1)
  }
  emit (name, data) {
    this.map[name] = this.map[name] || []
    for (let event of this.map[name]) {
      event.call(this, data)
    }
  }
}
const e = new EventHub()
const func1 = function (name) {
  console.log('hello' + name)
}
const func2 = function (name) {
  console.log('bye' + name)
}
e.on('click', func1)
e.on('click', func2)
e.off('click', func1)
e.emit('click', 'mike')
  • 手写bind
let o = {}
function add (...args) {
  console.log(args.reduce((a, b) => a + b))
}
Function.prototype.mybind = function (obj, ...args) {
  let fn = this
  const fbound = function () {
    let nowthis = this instanceof fbound ? this : obj
    return fn.apply(nowthis, args.concat([...arguments]))
  }
  fbound.prototype = Object.create(this.prototype)
  return fbound
}
add.mybind(o, 1, 2)(3)
let temp = add.mybind(o, 10, 20)
new temp(30)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值