简体   繁体   中英

Transforming jquery function into functional programming function

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...

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); } 

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])) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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