首页 > 解决方案 > 递归展平一组数组的算法

问题描述

我刚刚写了这个非常简约的日志助手。- 它根据消息的级别过滤消息,实际上仅此而已。

由于我希望这些级别具有包容性,因此我需要计算当前级别中包含的级别的平面列表。递归减少与查找相结合似乎是合理的选择。

唯一的问题是,我知道如何描述这个函数的作用,就一个可重用的函数名称而言,我可以将它存储在通用减速器助手之间的某个地方。

递归减少执行的算法有名称吗?

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>

标签: javascriptalgorithmrecursionreduce

解决方案


尝试Array.flatMap(),希望它有所帮助。


推荐阅读