Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Monkey Patching JavaScript

6 views
Skip to first unread message

DAZ

unread,
Aug 18, 2024, 9:46:05 AM8/18/24
to North West Ruby User Group (NWRUG)
What are people's thoughts about monkey patching JavaScript to make it more like Ruby?

I find myself constantly missing being able to use some of Ruby's array methods ... and the fact that you can't do "hello".reverse is just ridiculous!

It would be really nice to be able to do things like [1,2,3].any and [1,2,3].empty and [1,2,3].sum instead of using a reduce!

I know that monkey patching is more of a Ruby thing and frowned upon in JavaScript. I've heard the arguments against it, but kind of think it's worth it to have a nice experience coding in JS.

There's a library called rearmed.js that does something like this, but I'd like to have a go at writing my own.

Any thoughts?

Lee Hambley

unread,
Aug 19, 2024, 4:56:02 AM8/19/24
to nwrug-...@googlegroups.com
Because Javascript is a "prototype" oriented language (although, modern introduction of Class keyword, and the rise of TypeScript has obscured that somewhat) you can simply do this which was even considered idiomatic a decade ago:

Array.prototype.reverse = function() {
  let start = 0;
  let end = this.length - 1;

  while (start < end) {
    // Swap elements
    let temp = this[start];
    this[start] = this[end];
    this[end] = temp;

    // Move to the next pair
    start++;
    end--;
  }

  return this;
};

// Example usage:
const arr = [1, 2, 3, 4, 5];
arr.reverse(); // [5, 4, 3, 2, 1]




--
You received this message because you are subscribed to the Google Groups "North West Ruby User Group (NWRUG)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nwrug-member...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/nwrug-members/a65512af-0b73-4cb0-8250-0b675bd07e1bn%40googlegroups.com.

Darren Jones

unread,
Aug 20, 2024, 3:11:19 AM8/20/24
to nwrug-...@googlegroups.com
Yeah I’ve added quite a few methods. 

You can also add properties as well which is nice. 

JavaScript is a really flexible language but missing quite a bit of stuff. 



Darren Jones

unread,
Aug 20, 2024, 3:11:41 AM8/20/24
to nwrug-...@googlegroups.com
I’ll share what I hack together …
Reply all
Reply to author
Forward
0 new messages