Revision 9d5387f9-31da-4eea-9227-1dc15263c852 - Stack Overflow

Below are a few alternatives. Each `recursiveMap` 

* does not mutate input
* produces a new array as output
* produces a valid result when an empty input is given, `[]`
* uses a single pure, functional expression

---

Destructuring assignment

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 const identity = x =>
 x

 const recursiveMap = (f = identity, [ x, ...xs ]) =>
 x === undefined
 ? []
 : [ f (x), ...recursiveMap (f, xs) ]
 
 const square = (x = 0) =>
 x * x
 
 console.log (recursiveMap (square, [ 1, 2, 3, 4, 5 ]))
 // [ 1, 4, 9, 16, 25 ]

<!-- end snippet -->

---

Array slice

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 const identity = x =>
 x

 const recursiveMap = (f = identity, xs = []) =>
 xs.length === 0
 ? []
 : [ f (xs[0]), ...recursiveMap (f, xs.slice (1)) ]
 
 const square = (x = 0) =>
 x * x
 
 console.log (recursiveMap (square, [ 1, 2, 3, 4, 5 ]))
 // [ 1, 4, 9, 16, 25 ]
 

<!-- end snippet -->

---

Additional parameter with default assignment – creates fewer intermediate values

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 const identity = x =>
 x

 const recursiveMap = (f = identity, xs = [], i = 0) =>
 i >= xs.length
 ? []
 : [ f (xs[i]) ] .concat (recursiveMap (f, xs, i + 1))
 
 const square = (x = 0) =>
 x * x
 
 console.log (recursiveMap (square, [ 1, 2, 3, 4, 5 ]))
 // [ 1, 4, 9, 16, 25 ]

<!-- end snippet -->

---

Tail recursive (and cute)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 const identity = x =>
 x
 
 const prepend = x => xs =>
 [ x ] .concat (xs)
 
 const compose = (f, g) =>
 x => f (g (x))

 const recursiveMap = (f = identity, [ x, ...xs ], then = identity) =>
 x === undefined
 ? then ([])
 : recursiveMap
 ( f
 , xs
 , compose (then, prepend (f (x)))
 )

 const square = (x = 0) =>
 x * x

 console.log (recursiveMap (square, [ 1, 2, 3, 4, 5 ]))
 // [ 1, 4, 9, 16, 25 ]
 // => undefined

 recursiveMap (square, [ 1, 2, 3, 4, 5 ], console.log)
 // [ 1, 4, 9, 16, 25 ]
 // => undefined

 recursiveMap (square, [ 1, 2, 3, 4, 5 ])
 // => [ 1, 4, 9, 16, 25 ]

<!-- end snippet -->


AltStyle によって変換されたページ (->オリジナル) /