Skip to content

Instantly share code, notes, and snippets.

@mcsf
Created July 21, 2021 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcsf/478fd1e05a1658c21c3af152a1856079 to your computer and use it in GitHub Desktop.
Save mcsf/478fd1e05a1658c21c3af152a1856079 to your computer and use it in GitHub Desktop.
/**
* 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