Transforming jquery function into functional programming function

荒凉一梦 提交于 2019-12-11 16:03:30

问题


I'm a beginner in functional programming and I want to transform this jquery function with the functional programming paradigm.

I try to transform this function

merge: function( first, second ) {
            var len = +second.length,
                j = 0,
                i = first.length;

            for ( ; j < len; j++ ) {
                first[ i++ ] = second[ j ];
            }

            first.length = i;

            return first;
        }

It is just a simple merge function.
For example, when I call

merge([0,1,2,3,4],[5,6,7,8,9]);

It produces

[0,1,2,3,4,5,6,7,8,9]

What I did is

merge: function( first, second ){
    var len = +second.length,
                j = 0,
                i = first.length;
    let modify = x =>{
    let merging =
        j => {
        first[ i++ ] = second[ j ];
        };
    R.map(merging, R.range(0,len))
    return first;
    }
    modify
}

But it does not work.
I know something is wrong in my code but I cannot guess where is it...


回答1:


Functional programming forbids mutation (for example, any obj[prop] = assignment is mutation). If you want to make this functional (and easy), just concat the first array with the second:

console.log(merge([0,1,2,3,4],[5,6,7,8,9]));

function merge(first, second){
  return first.concat(second);
}



回答2:


You can also simply destructure them with ES6 into a new one:

console.log([...[0,1,2,3,4], ...[5,6,7,8,9]])

// OR if you really want a pure function

let mergeArrays = (a,b) => [...a, ...b]

console.log(mergeArrays([0,1,2,3,4], [5,6,7,8,9]))


来源:https://stackoverflow.com/questions/56197421/transforming-jquery-function-into-functional-programming-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!