gpt4 book ai didi

javascript - NodeJS模块开发的疑惑

转载 作者:行者123 更新时间:2023-11-30 12:52:36 26 4
gpt4 key购买 nike

我正在尝试编写我的第一个 NodeJS 模块,但我无法理解一些概念。

这是我目前拥有的代码(genexer 计数器/生成器):

"use strict";

var ret = require('ret');

module.exports = function (regex) {
if (Object.prototype.toString.call(regex) === '[object RegExp]') {
regex = regex.source;
}

else if (typeof regex !== 'string') {
regex = String(regex);
}

try {
var tokens = ret(regex);
}

catch (exception) {
return false;
}

return {
charset: '',
reference: [],
count: function (token) {
var result = 0;

if ((token.type === ret.types.ROOT) || (token.type === ret.types.GROUP)) {
if (token.hasOwnProperty('stack') === true) {
result = 1;

token.stack.forEach(function (node) {
result *= count(node);
});
}

else if (token.hasOwnProperty('options') === true) {
var options = [];

token.options.forEach(function (stack, i) {
options[i] = 1;

stack.forEach(function (node) {
options[i] *= count(node);
});
});

options.forEach(function (option) {
result += option;
});
}

if ((token.type === ret.types.GROUP) && (token.remember === true)) {
reference.push(token);
}
}

else if (token.type === ret.types.POSITION) {
}

else if (token.type === ret.types.SET) {
token.set.forEach(function (node) {
if (token.not === true) {
if ((node.type === ret.types.CHAR) && (node.value === 10)) {
}
}

result += count(node);
});
}

else if (token.type === ret.types.RANGE) {
result = (token.to - token.from + 1);
}

else if (token.type === ret.types.REPETITION) {
if (isFinite(token.max) !== true) {
return Infinity;
}

token.value = count(token.value);

for (var i = token.min; i <= token.max; ++i) {
result += Math.pow(token.value, i);
}
}

else if (token.type === ret.types.REFERENCE) {
if (reference.hasOwnProperty(token.value - 1) === true) {
result = 1;
}
}

else if (token.type === ret.types.CHAR) {
result = 1;
}

return result;
}(tokens),
generate: function () {
return false;
},
};
};

问题:

  1. 我是否在第一次迭代时正确地调用了 countcount: function (token) {}(tokens)?
  2. 如何递归调用 count 方法?我收到“ReferenceError:计数未定义”
  3. 这是使用多种方法定义小模块的正确(或最佳实践)方法吗?

请原谅我没有发布 3 个不同的问题,但我还不是很熟悉所有的术语。

最佳答案

  1. 立即调用闭包的约定是 count: (function(args) {return function() {}})(args) 但您的方式也适用于所有环境。
  2. 你不能,因为不幸的是 count 是一个闭包——见 3。
  3. 如果您想在模块内部使用模块上的方法,我会在 return 语句之外声明模块。如果你想要一个很好的例子,请参阅 underscore/lodash 源代码。

所以你可以使用像下面的框架这样的声明来定义你的模块

module.exports = function (regex) {
//...
var count = function(tokens) {
//...
return function() {
//...
var ret *= count(node);


return ret;
}
}
var mymod = {
count: count(tokens)
//...
};
//...
return mymod;

};

关于javascript - NodeJS模块开发的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20408044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com