简体   繁体   English

使用Underscore / Lodash在javascript中进行非变异反尾的最佳方法

[英]Best way to do a non-mutating inverse tail in javascript using Underscore/Lodash

I'm an avid user of lodash/underscore in my node.js projects, and I find myself in a situation where I need to recursively iterate through an array from right to left in a manner similar to the below code (assuming that all calls are synchronous): 在我的node.js项目中,我是lodash / underscore的狂热用户,我发现自己处于这样一种情况,我需要以类似于下面代码的方式从右到左递归迭代一个数组(假设所有调用是同步的):

function makeDir(pathArray) {
  var unsulliedPath = clone(pathArray);
  var lastGuy = pathArray.pop();
  var restOfEm = pathArray;
  if dirExists(unsulliedPath) {
    console.log("Your job is done!");
  } else {
    makeDir(restOfEm);
    makeDir(unsulliedPath);
  }
}

Having to clone and mutate the pathArray argument bugs me, however. 但是,必须克隆并改变pathArray参数会让我感到困惑。 So I could do this: 所以我可以这样做:

function makeDir(pathArray) {
  var lastGuy = _.last(pathArray);

  // EITHER I could...
  var restOfEm = _(pathArray).reverse().tail().reverse().value(); 
  // OR I could do...
  var restOfEm = _.first(pathArray, pathArray.length - 1);

  if dirExists(pathArray) {
    console.log("Your job is done!");
  } else {
    makeDir(restOfEm);
    makeDir(pathArray);
  }
}

Okay, that takes care of having to clone the argument passed in. That underscore incantation is slightly ugly, though. 好吧,这需要克隆传入的参数。但是,下划线的咒语有点难看。

Do lodash/underscore contain a simpler and clearer method for getting the inverse of _.rest(), that is, every element except the last? lodash / underscore是否包含一个更简单,更清晰的方法来获取_.rest()的反转,即除了最后一个元素之外的每个元素? If not, is there a preferred idiomatic solution for implementing this method in Javascript for use alongside lodash/underscore-style functional libraries, or is this simply nit-picking? 如果没有,是否有一个首选的惯用解决方案,用于在Javascript中实现此方法以与lodash /下划线样式的函数库一起使用,或者这只是简单的挑选?

Thanks in advance, and apologies for any glaring omissions or errors in my question. 在此先感谢,并对我的问题中的任何明显遗漏或错误道歉。

Why bother with underscore/lodash. 为什么要打扰下划线/ lodash。

var last = pathArray.slice(-1)[0];
var rest = pathArray.slice(0, -1);

slice will do this all for you very easily... slice会很容易地为你做这一切......

Use Array.splice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice and if you do not want to modify the original, do Array.slice to copy the original and then Array.splice. 使用Array.splice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice如果您不想修改原始文件,请执行Array.slice复制原始文件然后是Array.splice。

ie: 即:

var rest = pathArray.slice(0);
var last = rest.splice(-1, 1)[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM