如何将JavaScript类转换为工厂函数

时间:2018-08-23 04:06:29

标签: javascript functional-programming

我有一个这样的班级:

setX()
这来自我碰到的blog post。懒惰地创建一个数字列表。

我试图将代码转换为工厂功能,但失败了。这是我失败的方法:

class Lazy {
  constructor(iterable, callback) {
    this.iterable = iterable
    this.callback = callback
  }

  filter(callback) {
    return new LazyFilter(this, callback)
  }

  map(callback) {
    return new LazyMap(this, callback)
  }

  next() {
    return this.iterable.next()
  }

  take(n) {
    const values = []
    for (let i = 0; i < n; i++) {
      values.push(this.next().value)
    }

    return values
  }
}

class LazyFilter extends Lazy {
  next() {
    while (true) {
      const item = this.iterable.next()

      if (this.callback(item.value)) {
        return item
      }
    }
  }
}

class LazyMap extends Lazy {
  next() {
    const item = this.iterable.next()

    const mappedValue = this.callback(item.value)
    return {
      value: mappedValue,
      done: item.done
    }
  }
}

我不知道这里出了什么问题。如果您问我为什么要这样做,我现在正在尝试使用JavaScript的工厂函数。

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您的目标是什么。工厂函数只是一个创建并返回对象的函数,因此您的方案中最简单的工厂函数就是这样:

const createInstance = (...args) => new Lazy(...args);

如果您打算完全删除Lazy,而是将其替换为生成对象文字的工厂函数,那么可能是这样的事情:

const createLazy = (iterable, callback) => {
  return {
    iterable,
    callback,
    filter: function (callback) {
      return createLazyFilter(this, callback)
    }
    // etc for the other functions
  }
}

const createLazyFilter = (iterable, callback) => {
  return Object.assign(createLazy(iterable, callback), {
    next: function () {/* etc */}
  });
};

const createLazyMap = (iterable, callback) => {
  return Object.assign(createLazy(iterable, callback), {
    next: function () {/* etc */}
  });
};
相关问题