该对象用于更改日志,并以这种方式编写:
{
header: version,
features: ["features"], // array with all the features (if there are any)
bugfixes: ["bugfixes"], // same for the bugfixes
other: ["other changes"] // there can be other types in the object
};
此对象需要填充此数组中的信息:
["[3.0.0]", "Features", "changes done in file", "Bug Fixes", "fixed home"],
["[2.0.1]", "Bug Fixes", "fixed login"],
["[2.0.0]","Features", "added home", "added footer", "Bug Fixes", "fixed login", "Breaking", "added a breaking change"]
可以有多个功能,多个错误修正以及其他类型的标题,例如breaking
。我想将这些数组添加到对象中,使每个版本的最终结果看起来像这样:
{
header: "3.0.0",
features: ["changes done in file"],
bugfixes: ["bugfixes"],
};
答案 0 :(得分:1)
编辑: 如果更改始终以小写字母记录,则可以避免原始答案中的键:
let generateLog = changes => {
let _key;
return changes.reduce((log, entry, idx) => {
if (idx === 0) {
log.header = entry.slice(1, -1);
} else {
let charCode = entry.charCodeAt(0);
let isKey = charCode >= 65 && charCode <= 90;
if (isKey) {
let _value = entry.split(' ').join('').toLowerCase();
if (!Array.isArray(log[_value])) {
log[_value] = [];
}
_key = _value;
} else {
log[_key].push(entry);
}
}
return log;
}, {});
}
JsFiddle:http://jsfiddle.net/y564xewm/2/
有很多方法可以解决这个问题。我发现为更新日志对象维护一个“键”映射是最简单的。如何处理该地图取决于您(您可以使用1:1数组映射,如:stringKeys = [a, b, c]; objKeys = [x, y, z]
)。
一旦定义了密钥,就需要在循环数组时查找密钥并将密钥应用于更改日志对象。您需要为下一个数组迭代维护该键,然后将值推送到数组。
遇到下一个键时,只需重复上一个键。
JSFiddle:http://jsfiddle.net/y564xewm/
解决方案:
// Register Change Log Keys
const CHANGE_LOG_KEYS = new Map();
// Key is response in array, Value is key assigned in object
// Adding a new key, like "Breaking" would be:
// CHANGE_LOG_KEYS.set('Breaking', 'breaking');
// Assuming response: [[x.x.x], 'Breaking', '...']
CHANGE_LOG_KEYS.set('Features', 'features');
CHANGE_LOG_KEYS.set('Bug Fixes', 'bugfixes');
let generateLog = changes => {
let _key;
return changes.reduce((log, entry, idx) => {
if (idx === 0) {
log.header = entry.slice(1, -1);
} else {
let value = CHANGE_LOG_KEYS.get(entry);
if (value) {
if (!Array.isArray(log[value])) {
log[value] = [];
}
_key = value;
} else {
log[_key].push(entry);
}
}
return log;
}, {});
}
let changes = [
["[3.0.0]", "Features", "changes done in file", "Bug Fixes", "fixed home"],
["[2.0.1]", "Bug Fixes", "fixed login"],
["[2.0.0]","Features", "added home", "added footer", "Bug Fixes", "fixed login", "Breaking", "added a breaking change"]
];
changes.forEach(change => {
console.log(generateLog(change));
});