这是一次公开的谈话。
当有人进入聊天时,将显示以下消息。“昵称出现了。”
当某人离开聊天时,将显示以下消息。“昵称已离开。”
在聊天中更改昵称有两种方式:离开聊天后,可以使用新昵称重新进入。在聊天中更改昵称。
更改昵称时,聊天中显示的先前消息的昵称也会更改。
例如,如果一个人在聊天中依次使用昵称"Muzi“和"Prodo”,则聊天中会显示以下消息。
“木子进来了。”"Prodo进来了。“
当“Muzi”离开房间时,会留下如下信息。“木子进来了。”"Prodo进来了。““木子走了。”
当Muzi再次使用新昵称Prodo返回时,前面的消息将更改为Prodo,如下所示。
"Prodo进来了。“"Prodo进来了。““普罗多走了。”"Prodo进来了。“
由于聊天允许重复昵称,因此目前聊天中有两个人使用昵称Prodo。现在,当Prodo (第二个人)将他的昵称更改为Ryan时,聊天消息如下所示。
"Prodo进来了。““瑞安进来了。”“普罗多走了。”"Prodo进来了。“
限制记录是包含以下字符串的数组,长度为1~ 100,000。
以下是对记录中字符串的描述。-所有用户由用户ID分隔。-用户ID以昵称进入聊天-“输入用户ID”(例如"Enter uid1234 Muzi") -用户ID离开聊天-“离开用户ID”(例如"Leave uid1234") -用户ID将昵称更改为昵称-“更改用户ID”(例如"Change uid1234 Muzi") -第一个单词是Enter、Leave或Change。-每个单词由空格分隔,并且仅由大写字母、小写字母和数字组成。-用户ID和昵称区分大小写字母。-用户ID和昵称的长度为1~ 10。-没有错误输入,例如离开聊天的用户正在更改昵称。
有人能帮我解决这个问题吗?我对javascript语言编程是个新手
发布于 2021-08-16 08:01:43
function solution(record) {
let history = [];
// looping
record.forEach((item) => {
const splitRecord = item.split(" ");
const keyword = splitRecord[0];
const uid = splitRecord[1];
const name = splitRecord[2] ? splitRecord[2] : "";
switch (keyword) {
case "Enter":
{
// Check already left user with the uid, then change left user's nickName to new one
const existUser = history.find((item) => item.user.uid === uid);
if (existUser) {
history = history.map((item) => {
if (item.user.uid === uid) {
return {
...item,
user: {
uid,
name
},
};
}
return item;
});
}
// Then push new user to the rooms with the uid
history.push({
user: {
uid,
name
},
message: "came in",
});
break;
}
case "Leave":
{
// Check user, then make him leave from rooms
const existIndex = history.findIndex((item) => item.user.uid === uid);
if (existIndex > -1) {
const name = history[existIndex].user.nickName;
history.push({
user: {
uid,
name
},
message: "has left",
});
}
break;
}
case "Change":
{
// Change all user's nickName to new one with same uid
history = history.map((item) => {
if (item.user.uid === uid) {
return {
...item,
user: {
uid,
name
},
};
}
return item;
});
break;
}
default:
break;
}
});
return history.map((item) => `${item.user.name} ${item.message}`);
}
console.log(
solution([
"Enter uid1234 Muzi",
"Change uid1234 Prodo",
"Leave uid1234",
"Enter uid1234 Ryan",
"Leave uid1234",
])
);
https://stackoverflow.com/questions/61451342
复制相似问题