JS实现:统计昵称对应花朵数量(单循环无数组限制)
统计用户花朵数量的函数实现问题
需求描述
我有如下字符串输入:
const text = '<Jane>:flower: <Kate><john> :like: received:flower::flower:'
需要编写函数统计每个用户的花朵(:flower:)数量,规则如下:
- 昵称以
<nickname>格式存在,大小写不敏感,需统一存为小写; - 解析昵称后,统计后续出现的
:flower:数量;连续出现的昵称需关联后续所有花朵数,每个重复昵称都累加该数量; - 同一昵称多次出现时,后续花朵数需累加到已有计数;
- 若连续链中重复出现同一昵称,如
<John><John><John> :flower: <Kate>,John会获得3朵花,Kate无花。
实现限制
- 仅能使用1个for循环;
- 仅能使用1个对象存储结果,格式如
{ jane: 1, kate: 2, john: 2 }; - 不能使用数组、嵌套循环、除
toLowerCase()外的原生JS方法或正则。
当前卡点
已写出能提取所有昵称的代码,但无法在不使用数组的情况下实现连续昵称的关联计数,现有代码如下:
function countFlowers(text) { const nickTag = "<>"; const result = {}; let isParsingNick = false; let currentNick = ''; let nickTagIndex = 0; for (let i = 0; i < text.length; i++) { const current = text[i]; if (!isParsingNick && current === nickTag[nickTagIndex]) { if (nickTagIndex === 0) { isParsingNick = true; currentNick = ''; } nickTagIndex++; } else if (isParsingNick && current === nickTag[nickTagIndex]) { if (nickTagIndex === 1) { isParsingNick = false; result[currentNick] = 0; nickTagIndex = 0; continue; } nickTagIndex++; } else if (isParsingNick && current !== nickTag[nickTagIndex]) { currentNick += current.toLowerCase(); } } return result; } const text = '<Jane>:flower: <Kate><john> :like: received:flower::flower:' console.log(countFlowers(text))
输入输出示例
- 输入:
const text = '<Jane>:flower: <kate>:like:<John> :like: received:flower::flower:'
输出:
{ jane: 1, kate: 2, john: 2 }
- 输入:
const text = '<Jane>:flower: <kate>:flower: :flower: :flower: <John> :like: received:flower::flower:'
输出:
{ jane: 1, kate: 3, john: 2, }
- 输入:
const text = '<Jane>:flower: <kate>:flower flower: flower:<John> :like: received:flower::flower:'
输出:
{ jane: 1, kate: 2, john: 2, }
- 输入:
const text = '<Jane>:flower: <kate>:like:<John> :like: received:flower::flower: <Jane> alsdaksdjhsa <Jane> :flower: :flower:'
输出:
{ jane: 5, kate: 2, john: 2 }
- 输入:
const text = '<Jane>:flower: <kate><Kim><Jacob><Emily> :like: received:flower::flower: <Kim><Jacob><Jane>'
输出:
{ jane: 1, kate:2, kim:2, jacob:2, emily:2 }
- 输入:
const text = ':flower: :flower: <Jane>:flower: <kate><John> :like: received:flower::flower: '
输出:
{ jane: 1, kate: 2, john: 2, }
内容的提问来源于stack exchange,提问作者daeeeddd
相关产品推荐
相关产品推荐

