在javascript中将递归函数转换为箭头函数

时间:2018-06-17 08:12:48

标签: javascript ecmascript-6 arrow-functions

如何将以下功能转换为箭头功能?我在这里使用currying

function mergeString(str){
   return function(str1){
     if(str1){
        return mergeString(str + ' ' + str1); 
     }
     else
     {
       return str;
     }
   }
}

2 个答案:

答案 0 :(得分:4)

您可以链接功能头,然后链接功能体。

const mergeString = str => str1 => str1 ? mergeString(str + ' ' + str1) : str;

console.log(mergeString('a')());
console.log(mergeString('a')('b')('c')());
console.log(mergeString('this')('should')('work')('as')('well')());

答案 1 :(得分:1)

Actuall这是休息参数的一个很好的用例:

mergeString(
  "one",
  "two",
  "three"
)

可用作:

package com.example.thisi.londonguide;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class AttractionFragPagerAdapter extends FragmentPagerAdapter {

    AttractionFragPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new RestaurantFragment();
        } else if (position == 1) {
            return new MuseumFragment();
        } else if (position == 2) {
            return new ParksFragment();
        } else return new HotelsFragment();
    }

    @Override
    public int getCount() {
        return 4;
    }

    private String[] tabTitles = new String[]{String.valueOf(R.string.tab_title_1),String.valueOf(R.string.tab_title_2),String.valueOf(R.string.tab_title_3),String.valueOf(R.string.tab_title_4)};


    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        super.getPageTitle(position);
        return tabTitles[position];
    }
}