Created
July 21, 2021 10:56
-
-
Save mcsf/478fd1e05a1658c21c3af152a1856079 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Map a function over an array, but only return a new array object if the | |
* application of the function to some value isn't identical to the value. | |
* | |
* @example | |
* xs !== xs.map(x => x) | |
* xs === lazyMap(xs, x => x) | |
* | |
* @param {Array} xs Array to be mapped over. | |
* @param {Function} f Function to map over array. | |
* @return {Array} Th input array if possible, or the map as a new object. | |
*/ | |
function lazyMap( xs, f ) { | |
let result = xs; | |
for ( const i in xs ) { | |
const x = xs[ i ]; | |
const v = f( x ); | |
if ( v !== x ) { | |
if ( result === xs ) result = xs.slice(); | |
result[ i ] = v; | |
} | |
} | |
return result; | |
} | |
export default lazyMap; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment