Skip to content

Instantly share code, notes, and snippets.

@Bamieh
Last active October 27, 2017 15:04
Show Gist options
  • Save Bamieh/9fccbf4bc394d0da2fd0c8bb5d314476 to your computer and use it in GitHub Desktop.
Save Bamieh/9fccbf4bc394d0da2fd0c8bb5d314476 to your computer and use it in GitHub Desktop.
Map over items that meet a certain condition, otherwise just pass the item as is.
/*
Description:
Map over an array of items:
- If the item meets the condition, apply the callback
- If the item does not meet the condition return the item without any transformation.
Example:
```
const exampleArray = [1, 2, 9, "C", "B", "C"];
exampleArray.mapOn(Math.sqrt, Number.isInteger); // [1, 1.414, 3, "A", "B", "C"];
```
Parameters
- callback
Function that produces an element of the new Array, taking three arguments:
- currentValue
The current element being processed in the array.
- index
The index of the current element being processed in the array.
- array
The array map was called upon.
- condition
Function perdicate, if returned value is truthy, the callback is applied, taking three arguments:
- currentValue
The current element being processed in the array.
- index
The index of the current element being processed in the array.
- array
The array map was called upon.
- thisArg
Optional. Value to use as this when executing callback.
Return value
A new array with each element being the result of the callback function if it meets the condition, otherwise the same item is returned.
*/
Array.prototype.mapOn = function(callback, condition, thisArg=this) {
return this.map((currentValue, index, array) => {
if(condition(currentValue, index, array)) {
return callback.call(thisArg, currentValue, index, array)
}
return currentValue
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment