function faultSeverityToAvailabilityStatus(faultSeverity) {
return mapOf(mzframeConstants.faultSeverity.working, availabilityStatus.ONLINE,
mzframeConstants.faultSeverity.outOfOrder, availabilityStatus.FAILED,
mzframeConstants.faultSeverity.degraded, availabilityStatus.DEGRADED,
mzframeConstants.faultSeverity.info, availabilityStatus.ONLINE
)[faultSeverity];
}
function mapOf() {
var ret = Object.create(null);
if (arguments.length % 2 !== 0) {
throw new Error("Arguments count not divisable by 2");
}
for (var i = 0; i < arguments.length; i += 2) {
var key = arguments[i];
var value = arguments[i + 1];
ret[key] = value;
}
return ret;
}
//=======>也可以用ES6的map和set进行重构该方法, 而且方便复用
function faultSeverityToAvailabilityStatus(faultSeverity) {
const map = new Map();
map
.set(mzframeConstants.faultSeverity.working, availabilityStatus.ONLINE)
.set(mzframeConstants.faultSeverity.outOfOrder, availabilityStatus.FAILED)
.set(mzframeConstants.faultSeverity.degraded, availabilityStatus.DEGRADED)
.set(mzframeConstants.faultSeverity.info, availabilityStatus.ONLINE);
return map.get(faultSeverity);
}
var Promise = require("bluebird");
var fs = Promise.stringifyAll(require("fs"));
function changeFileToNonRootWritable(path) {
return fs.chmodAsync(path, "664").catch((err) => {
logger.error("chmod '%s' fails: %s", path, err);
return Promise.reject();
});
}
function changeFileToNonRootReadable(path) {
return fs.chmodAsync(path, "644").catch((err) => {
logger.error("chmod '%s' fails: %s", path, err);
return Promise.reject();
});
}
var Promise = require('promise');
var child_process = Promise.promisifyAll(require('child_process'));
function changeGroup(gid /*: string(groupID) */, path /*: filePath */) /*: promise(reject | resolve) */ {
if (gid) {
var command = "chgrp " + gid + " " + path;
logger.info("Executing command ", command);
return child_process.execAsync(command).catch(function(err) {
logger.error("Could not change group for " + path + " (err: " + err.code + ")");
return Promise.reject();
});
} else {
return Promise.resolve();
}
}
// 值得学习函数返回带参数的函数。
Mescom.prototype.successfulStatusOrThrow = function successfulStatusOrThrow(message) {
return function(response) {
if (!hasSuccessfulStatus(response)) {
throw new Mescom.MescomError(message, response);
} else {
return response;
}
};
};
// 函数调用
mescom
.sendAndWaitResponse(msg, mescom.Filter.byId(mescom.messageId.RROM_CONFIGURATION_RESP_MSG))
// 注意 mescom.successfulStatusOrThrow("RROM configuration failed") 实际上返回的是一个带参数的匿名函数,所以当前面filter出来的结果就作为这个函数的参数传进去了。
.then(mescom.successfulStatusOrThrow("RROM configuration failed"))
.error(logError)
.catch(Promise.TimeoutError, handleTimeout);
//场景1
function isStrNotInAryThenPush(ary, str) {
ary.indexOf(str) != -1 || ary.push(str);
//ES6
ary.includes(str) || ary.push(str);
}
// 场景2
var _ = require('lodash');
function pushData(collections/*: object */, value, key/*: string */)/*: object */ {
(collections[key] || collections[key]=[]).push(value);
return collections
}
pushData({a:[1], b:[2, 4]}, 3, 'c');
// => {a:[1], b:[2, 4], c:[3]}
// 场景3
var _ = require('lodash');
_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
//如果存在就push到存在的数组里,否则就创建新数组push进去
(result[value] || (result[value] = [])).push(key);
return result;
}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
function isSameMacAddress(inputMacAddress) {
return onlineImTree.getImTree()
.then(nodeFinder.getActiveBtsLNode)
.then(compareMacAddressFromActiveLNode);
function compareMacAddressFromActiveLNode(activeBtsLNode) {
const macObjects = activeBtsLNode ? activeBtsLNode.findByClassPath(ETHIF_R) : [];
return macObjects.map(getMacAddress).some(isSameWithInputMacAddress);
}
function getMacAddress(macObject) {
const parameters = macObject.getDecodedParameters();
return parameters ? parameters.macAddr : '';
}
function isSameWithInputMacAddress(macAddr) {
return macAddr.replace(macReplaceRegex, '') === inputMacAddress.replace(macReplaceRegex, '');
}
}
/**
* [groupPrsByYear description]
* @param {[type]} arr [description]
* @return {[type]:} [{year1:{date: "year1", data:[{d1}, {d2}]}}]
*/
function groupPrsByYear(arr/*: array */) /*: array */{
var mytmpData = {};
(arr||[]).forEach(function(d) {
//group data by year.
var tmpTime = (moment(d.createtimestamp*1000).format('YYYY'));
var tmpFind = _.has(mytmpData, tmpTime);
if(tmpFind) {
mytmpData[tmpTime]["data"].push(d);
}else {
mytmpData[tmpTime] = {date:tmpTime, data: [d]};
}
});//end (arr||[]).forEach(function(d)
return mytmpData;
}
// 代码可以像下面这样简化:
function groupBy_interval(results, interval){
return _.groupBy(results, d => faultCommons.formatDate(d.createtimestamp*1000, interval));
}
//faultCommons.formatDate 如下:
function formatDate(timestamp, interval) {
var formats = {day: 'YYYY-MM-DD', isoweek: 'YYYY[-]WW', month: 'YYYY[-]MM', year: 'YYYY', week: 'YYYY[-]ww'};
return timestamp.toString().length === 11 //unix timestamp
? moment(timestamp*1000).format(formats[interval])
: moment(timestamp).format(formats[interval]);
}
function find_first_item(obj, srcKey, target) {
return _.find(obj, d => faultCommons.isInArray(target, d[srcKey]));
}
function fault_ncdr_chartDraw(data, graph_ID, tableParams) {
// var data ={"results": [{"date":"2017-03","stats":[{"name":"NCDR(A&B)","num":39},{"name":"A-Critical","num":20},{"name":"B-Major","num":19},{"name":"C-Minor","num":8},{"name":"Baseline","num":43},{"name":"NCDR Cumulative","num":131},{"name":"A-Critical Cumulative","num":56},{"name":"B-Major Cumulative","num":75},{"name":"Monthly Target","num":0},{"name":"Target Cumulative","num":0}]},
// {"date":"2017-04","stats":[{"name":"NCDR(A&B)","num":0},{"name":"A-Critical","num":0},{"name":"B-Major","num":0},{"name":"C-Minor","num":0},{"name":"Baseline","num":46},{"name":"NCDR Cumulative","num":131},{"name":"A-Critical Cumulative","num":56},{"name":"B-Major Cumulative","num":75},{"name":"Monthly Target","num":0},{"name":"Target Cumulative","num":0}]}
// ]};
// filter only needed to be drawed data.
var validEchartData = {
"NCDR(A&B)":{"name":"NCDR(A&B)","num":[]},
"NCDR Cumulative": {"name":"NCDR Cumulative","num":[]},
"Monthly Target":{"name":"Monthly Target","num":[]},
"Target Cumulative": {"name":"Target Cumulative","num":[]},
"Baseline": {"name":"Baseline","num":[]}
};
var ECHAT_NAMES = ["NCDR(A&B)","NCDR Cumulative", "Monthly Target", "Target Cumulative", "Baseline"];
var data_restructure = {inside_data: [], xaxis:[]};
(data.results || []).forEach(function (d, i) {
data_restructure["xaxis"].push(d.date);
(d.stats||[]).forEach(function (dd) {
if (ECHAT_NAMES.indexOf(dd.name) != -1) {
validEchartData[dd.name]["num"].push(dd.num);
}
});
});
data_restructure.inside_data = _.values(validEchartData);
ncdr_echart_draw(data_restructure, formatTitleDate(data.interval), graph_ID);
draw_table(data, tableParams);
}
原boject更改值成功,在Lodash的_.sortBy之后!
函数,先对输入object进行排序,然后对最小的加true标签,其他的加false标签。
我也是稀里糊涂的就实现了这个功能, 但是实在没有明白为什么。
根据打印,lodash 的sortBy之后的结果和原来的obj是完全不一样的,而我的更改是基于sortby之后的结果,为什么obj也跟着变化了?
function test(obj,key) {
console.log("obj_orig======\n%j", obj);
console.log("obj_sortby=====\n%j", _.sortBy(obj, ['age', 'user']));
console.log("obj_after_sortby=====\n%j", obj);
_.sortBy(obj, ['age', 'user']).forEach(function(d, i) { d[key] = (0===i) ? true : false;});
console.log("after_change======\n%j", obj);
}
var users = [
{ 'user': 'Halen', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'Jack', 'age': 34 }
];
test(users ,"zzz");
运行结果输出==========================
obj_orig======
[{"user":"Halen","age":48},{"user":"barney","age":36},{"user":"fred","age":40},{"user":"Jack","age":34}]
obj_sortby=====
[{"user":"Jack","age":34},{"user":"barney","age":36},{"user":"fred","age":40},{"user":"Halen","age":48}]
obj_after_sortby=====
[{"user":"Halen","age":48},{"user":"barney","age":36},{"user":"fred","age":40},{"user":"Jack","age":34}]
after_change======
[{"user":"Halen","age":48,"zzz":false},{"user":"barney","age":36,"zzz":false},{"user":"fred","age":40,"zzz":false},{"user":"Jack","age":34,"zzz":true}]
当然上面函数可以这样变化这里写代码片
function add_mapping_key_val(obj, key){
(obj||[]).forEach(function(d, i){ d[key] = (0 === i) ? true : false; });
}
var users = [
{ 'user': 'Halen', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'Jack', 'age': 34 }
];
add_mapping_key_val(_.sortBy(users,['age', 'user']),"zzz");
function split_arr(arr, slice_num) { //split arr to subArr by every slice_num
var tmpArr = [];
while (arr.length > 0) {
tmpArr.push(arr.splice(0, slice_num));
}
return tmpArr;
}
// get TargetBD file
function getTargetBD(path) {
return fs.readdirAsync(path)
.filter(function(fileName) {
return /^[Tt]arget[Bb][Dd].*\.xml$/.test(fileName);
})
.then(function(list) {
if (!list.length) {
logger.error("TargetBD not found from " + path);
return Promise.reject();
} else if (list.length !== 1) {
logger.error("Found " + list.length + " TargetBD files from " + path);
return Promise.reject();
} else {
logger.info("Found ", list[0]);
return Promise.resolve(Path.join(path, list[0]));
}
});
}