javascript - 递归展平一组数组的算法
问题描述
我刚刚写了这个非常简约的日志助手。- 它根据消息的级别过滤消息,实际上仅此而已。
由于我希望这些级别具有包容性,因此我需要计算当前级别中包含的级别的平面列表。递归减少与查找相结合似乎是合理的选择。
唯一的问题是,我知道如何描述这个函数的作用,就一个可重用的函数名称而言,我可以将它存储在通用减速器助手之间的某个地方。
递归减少执行的算法有名称吗?
const logLevel = process.env.LOG_LEVEL;
const levels = {
info: 'info',
debug: 'debug',
warning: 'warning',
error: 'error'
}
const includes = {
[levels.debug]: [levels.info],
[levels.info]: [levels.warning],
[levels.warning]: [levels.error]
}
const format = {
simple: (strings, ...values) => strings.reduce ((l, r, i) => [l,JSON.stringify (vals[i]),r].join (''))
}
const uniqueRefSlow = (ele, ind, arr) => !~arr.indexOf (ele, ind + 1);
const Combine = lists => function concatTreeRecursive (levels, level) {
let more = lists[level]||[];
if (more.length) return more.reduce (concatTreeRecursive, [level, ...levels])
return [level, ...levels].filter (uniqueRefSlow);
};
const reduceRecursive = Combine (includes);
const combineLevels = levels => levels.reduce (reduceRecursive);
// ^ How is this operation called?
console.log (`Logging on level ${logLevel}`);
const Log = (levels = [LEVELS.info], tag = format.simple) => (strings, ...values) => {
let message = tag (strings, ...values);
if (!!~combineLevels (levels).indexOf (logLevel)) {
console.log (message);
}
return message;
}
const debug = Log ([levels.debug])
const info = Log ([levels.info]);
const warning = Log ([levels.info]);
debug`debug - filtered`
info`info`
warning`warning - included`
<script>const process = {env: {LOG_LEVEL: 'info'}}</script>
解决方案
尝试Array.flatMap(),希望它有所帮助。
推荐阅读
- r - 将 XTS 上的 Apply.monthly 应用于非零列
- java - launch.json 参数的文档在哪里
- javascript - 如何从 JavaScript 中的 Map 对象获取特定键
- python - 将渲染的 Holoview 绘图添加到交互式 Bokeh APP
- powerbi - Expression.Error:找不到表的“金额”列
- git - 连续撤消多个 Git 提交但保留所有更改
- python - 重力矢量的三角加速度计 Z 角(法线矢量到 XY 平面)
- linux - 如何从 Bash 脚本中列出目标 PID 的曾孙 PID?
- javascript - Javascript:如何计算到一个特定的数字?
- python - 聊天机器人使用 pdf 文档作为源