简体   繁体   English

从命令式到声明式字符限制

[英]Moving Imperative to Declarative- character limitations

One module in my app pulls records from a mongodb and prints out the fields for the user to see. 我的应用程序中的一个模块从mongodb中提取记录,并打印出字段供用户查看。 The fields are displayed in a particular order. 字段以特定顺序显示。 The order is stored in an array. 订单存储在数组中。 The mongodb document ( pers ) may not have all of the fields possible filled out. mongodb文档( pers )可能没有填写所有可能的字段。 Anyway, here is an example of my original code. 无论如何,这是我原始代码的示例。 It works. 有用。 I want to move onto something better. 我想继续前进。 I will explain as I go. 我会解释。

const keys = ['banana', 'orange', 'apple', 'grape']

const pers = {
    banana: 'word',
    orange: 'e t',
    apple: 'scrabble',
}
let entries = []
let entry = ''

keys.forEach(key => {
    if (pers[key]) entries.push(pers[key])
})

for (let i=0; i<entries.length; i++) {
    if ((entries.length + entries[i].length < 10) entry += '\n' + entries[i]
    else {
        console.log(entry) //message.send in my app
        entry = entries[i]
    }
}
console.log(entry)

So in my app, the message that is sent cannot be longer than 2000 characters. 因此,在我的应用程序中,发送的消息不能超过2000个字符。 I am using 10 characters for the example here in the post. 我在帖子中使用10个字符作为示例。 And I do not want them split up in the middle either. 而且我也不希望他们在中间分裂。 So for instance 'word' + 'et' is the maximum I can concatenate together. 因此,例如“ word” +“ et”是我可以连接在一起的最大值。 If I try to add 'scrabble' to it, the total length will be over 10 characters in length. 如果我尝试在其中添加“拼字游戏”,则总长度将超过10个字符。 So I want to send 'word et' to the console and then start the variable entry over. 所以我想“字等”发送到控制台,然后启动变量entry了过来。 I also do not want to send 'word' and then 'e' and then 't' and then 'scrabble'. 我也不想发送“单词”,然后发送“ e”,然后发送“ t”,然后发送“拼字游戏”。 Like I said before, my existing code works. 就像我之前说过的,我现有的代码有效。 I just want to try and be clear on my intent. 我只想尝试并明确我的意图。

Moving forward... Below is my second iteration of the code. 前进...下面是我的第二次代码迭代。 I'm trying to move away from imperative statements to declarative. 我正在尝试从命令式声明转为声明式。 So I replaced the forEach block. 因此,我替换了forEach块。 This also works great. 这也很好。

const keys = ['banana', 'orange', 'apple', 'grape']

const pers = {
    banana: 'word',
    orange: 'e t',
    apple: 'scrabble',
}
let entry = ''

const entries = keys.filter(key => pers.hasOwnProperty(key)).map(key => pers[key])

for (let i=0; i<entries.length; i++) {
    if ((entries.length + entries[i].length < 10) entry += '\n' + entries[i]
    else {
        console.log(entry)
        entry = entries[i]
    }
}
console.log(entry)

The console output for both of these is: 这两个的控制台输出是:

word
e t
scrabble

That is exactly what I wanted. 那正是我想要的。 Now I really want to move away from that for block if possible. 现在我真的想从搬走for ,如果可能的块。 Surely there is a way to add another chain to my declarative statement to take care of that portion? 当然,有一种方法可以在我的声明性语句中添加另一个链来处理该部分? I could possibly see a way of doing it if I didn't have the character limitation. 如果没有字符限制,我可能会找到一种解决方法。

Anyway, if I have been unclear in any of my description or intent, please let me know and I will do my best to clarify. 无论如何,如果我的描述或意图不清楚,请让我知道,我将尽力澄清。

Thanks!! 谢谢!!

Try using .reduce like this. 尝试像这样使用.reduce Your original code had a syntax error, so I'm assuming that was just a typo and not something important. 您的原始代码有语法错误,因此我假设那只是一个错字,而不是重要的东西。

While that's functionally identical to your current code, it's still pretty convoluted. 尽管在功能上与您当前的代码相同,但仍然令人费解。 If I were you, I'd create an array of entryStrs while iterating, and then console.log them all later, like this: 如果您是我,我会在迭代时创建一个entryStrs数组,然后稍后用console.log它们全部记录下来,如下所示:

 const keys = ['banana', 'orange', 'apple', 'grape'] const pers = { banana: 'word', orange: 'e t', apple: 'scrabble', } const { currentMessage, messages } = keys .filter(key => pers.hasOwnProperty(key)) .map(key => pers[key]) .reduce(({ currentMessage = '', messages = [] }, entry, i, entries) => { if (entries.length + entry.length < 10) { currentMessage += currentMessage ? ('\\n' + entry) : entry; } else { messages.push(currentMessage) currentMessage = entry; } return { currentMessage, messages }; }, {}); const allMessages = [...messages, currentMessage]; console.log(allMessages.join('\\n-----\\n-----\\n')); 

since in the for block you have to iterate and change an external variable and not changing anything in the array itself, you can use Conditional (tenary) Operator and replace for with forEach() 由于在for块中,您必须迭代和更改外部变量,并且不更改数组本身中的任何内容,因此可以使用条件(三元)运算符用forEach()代替

 const keys = ['banana', 'orange', 'apple', 'grape'] const pers = { banana: 'word', orange: 'e t', apple: 'scrabble', } let entry = '' const entries = keys.filter(key => pers.hasOwnProperty(key)).map(key => pers[key]) entries.forEach(e => { entries.length + e.length < 10 ? entry += '\\n' + e : (console.log(entry), entry = e) }); console.log(entry) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM