Skip to content

Instantly share code, notes, and snippets.

@chunkybyte
Created June 16, 2020 20:25
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 chunkybyte/73e51c319634c17119a1cbf44e192a15 to your computer and use it in GitHub Desktop.
Save chunkybyte/73e51c319634c17119a1cbf44e192a15 to your computer and use it in GitHub Desktop.
Simple Duck Punching Example in Vanilla JavaScript
// Duck Punching in JavaScript
const sentence = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const legacyIndexOf = String.prototype.indexOf;
// Extending the indexOf functionality to return the last occurence of the searchValue
String.prototype.indexOf = function (searchValue, fromIndex, getLastIndexFlag = false) {
if (!getLastIndexFlag) {
return legacyIndexOf.call(this, searchValue, fromIndex);
} else {
return legacyIndexOf.call(this.split(' ').reverse().join(' '), searchValue, fromIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment