将嵌套数组减少为格式化字符串 [英] Reduce nested array to formatted string

查看:91
本文介绍了将嵌套数组减少为格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想减少这个嵌套数组:

I want to reduce this nested array:

const list = ['Map<%s,%s>', ['string', 'Map<%s,%s>', ['string', 'boolean']]];

以便列表成为:

'Map<string,Map<string,boolean>>'

这是一个开始,但这种反应对我来说真的很困惑:

Here is a start, but the recusion is really confusing to me:

const util = require('util');

const reduceToString = function(l){
  return l.reduceRight((a,b) => {
    if(Array.isArray(a)){
      return reduceToString(a);
    }

    return util.format(b, a);

  });
};


console.log(reduce(list));

为了更好地了解这需要如何一般地工作,这个输入:

const list = ['Map<%s,%s,%s>', ['string', 'Map<%s,%s>', ['string', 'boolean'], 'number']];

应该收益:

'Map<string,Map<string,boolean>,number>'

一般规则是:字符串右边的任何数组都应该插入到字符串中,而reduceToString函数应该总是返回一个字符串。

The general rule is: any array to the right of a string, should be interpolated into the string, and the reduceToString function should always return a string.

推荐答案

一种方法可以是减少任何一个数组元素(下降到最深层次),然后在你从堆栈中为任何元素返回时进行替换其下一个元素是一个数组:

One approach can be to "reduce" any element that is an array (going down to the deepest level) and then do your replacements as you keep returning from the stack for any element whose "next element" is an array:

const list = ['Map<%s,%s,%s>', ['string', 'Map<%s,%s>', ['string', 'boolean'], 'Number']];

function merge(list) {
  function reduce(arr) {
    arr = arr.map(e => Array.isArray(e) ? reduce(e) : e);
    return arr
      .map((e, i) => Array.isArray(arr[i + 1])
        ? arr[i + 1].reduce((a, c) => a.replace('%s', c), e)
        : e)
      .filter(e => !Array.isArray(e));
  }
  return reduce(list)[0];
}


console.log(merge(list));

这篇关于将嵌套数组减少为格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆