• Stars
    star
    104
  • Rank 330,604 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A collection of helpful methods and monkey patches for Arrays, Objects, Numbers, and Strings in Javascript

Rearmed-JS

NPM Version CI Status NPM Downloads Buy Me a Coffee

This library is a collection of helpful methods and monkey patches for Arrays, Objects, Numbers, and Strings in Javascript. Start writing your Javascript like you write your Ruby code!

Works in the Browser and in NodeJS.

5.1kb minified and gzipped.

Install

Yarn, NPM, Bower

yarn add rearmed-js

npm install rearmed-js

bower install rearmed-js

Rails / Bundler

# Gemfile
source 'https://rails-assets.org' do
  gem 'rails-assets-rearmed-js'
end

Usage

Note: Only import/require the patches once at the beginning of your page or app start otherwise you will get warnings about redefining methods.

Plain HTML

<script src="rearmed-js/dist/rearmed.min.js" type="text/javascript" />

<!-- OR only the patches you want -->

<!-- All patches for a certain object type only -->
<script src="rearmed-js/dist/array.min.js" type="text/javascript" />
<script src="rearmed-js/dist/number.min.js" type="text/javascript" />
<script src="rearmed-js/dist/object.min.js" type="text/javascript" />
<script src="rearmed-js/dist/string.min.js" type="text/javascript" />
<script src="rearmed-js/dist/generic.min.js" type="text/javascript" />

<!-- OR only the methods you want -->
<script src="rearmed-js/dist/array/reject.min.js" type="text/javascript" />
<script src="rearmed-js/dist/array/select.min.js" type="text/javascript" />

ES7+

import 'rearmed-js'; // import everything

// OR 

// import patches for certain object types only
import 'rearmed-js/array';
import 'rearmed-js/number';
import 'rearmed-js/object';
import 'rearmed-js/string';
import 'rearmed-js/generic';

// OR

// import only the methods you want
import 'rearmed-js/array/reject';
import 'rearmed-js/array/select';

ES6

require('rearmed-js') // require everything

// OR

// require patches for certain object types only
require('rearmed-js/array');
require('rearmed-js/number');
require('rearmed-js/object');
require('rearmed-js/string');
require('rearmed-js/generic');

// OR

// require only the methods you want
require('rearmed-js/array/reject');
require('rearmed-js/array/select');

Rails

/*
 *= require rearmed-js
 *
 * OR for certain object types only
 *= require rearmed-js/array
 *= require rearmed-js/number
 *= require rearmed-js/object
 *= require rearmed-js/string
 *= require rearmed-js/generic
 *
 * OR only the methods you want
 *= require rearmed-js/array/reject
 *= require rearmed-js/array/select
*/

Methods Implemented

Generic

These methods are available on all types that inherit from Object which is almost everything.

var cb = function(){ };
var str = "";
var array = [];

str.equals(array); // returns bool

str.isBlank(); // returns bool
// collections are blank if length == 0

str.isPresent(); // return bool
// collections are present if length > 0

array.presence(); // returns self or false
// same thing as: array.isPresent() ? array : false;

cb.simpleType(); // return str
// possible return values are 'Object','Array','String','Boolean','Number','Function','Other'

// return value or false
str.try('length'); // => 0
array.try('sort'); // => []
str.try('badMethod').try('anotherBadMethod'); // => false

Array

var array = [];

var cb = function(val, i){ };

array.any(cb=null) // returns bool

array.all(cb=null) // returns bool

array.compact(badValues=[null, undefined, '']) // returns array, accepts array or splat arguments
  
array.dig(*args) // returns value, accepts splat arguments or array

array.each(function(val, i){ })

array.empty() // return bool

array.equals(array) // returns bool

array.excludes(val, fromIndex=0) //  returns bool

array.find(cb_or_val) // returns value, undefined if not found

array.findIndex(cb_or_val) // returns integer, undefined if not found

array.first() // returns value

array.flatten() // returns array

array.includes(val, fromIndex=0) // returns bool

array.inGroupsOf(int, fillWith=false) // returns nested array

array.groupBy(cb) // returns nested array

array.last // returns value

array.max(cb=null) // returns value

array.maxBy(cb=null) // returns value

array.min(cb=null) // returns value

array.minBy(cb=null) // returns value

array.reject(cb) // reutrns array

array.select(cb) // returns array

array.tap(cb); // returns array
// this is an each method that returns the original array after its done

array.smartIncludes(val, fromIndex=0) // returns bool
// smart meaning that it uses `equals` method to compare if item is Array or Object

array.smartExcludes(val, fromIndex=0) // returns bool
// smart meaning that it uses `equals` method to compare if item is Array or Object

array.sum(cb=null) // returns number

array.uniq(cb=null) // returns array


/* CLASS METHODS - Not available in Typescript */

Array.range(startNumber, endNumber, step=1) // returns array

Object (Hash)

var obj = {};

// Monkey-patching Object is very dangerous, so we only patch it with one method
obj = obj.rearmed(); 

var cb = function(key, val){ };

obj.all(cb=null) // returns bool

obj.any(cb=null) // returns bool

obj.compact(badValues=[null, undefined, '']) // returns object, accepts array or splat arguments

obj.dig(*args) // returns object, accepts splat arguments or array

obj.each(cb);

obj.empty() // returns bool

obj.equals(obj) // returns bool

obj.except(*keys) // returns object, accepts keys as splat arguments or an array

obj.hasKey() // returns bool

obj.hasValue() // returns bool

obj.join(cb, delimiter=', ') // returns string

obj.keys() // returns array

obj.merge(obj) // returns object

obj.only(*keys) // returns object, accepts keys as splat arguments or an array

obj.reject(cb) // returns object

obj.select(cb) // returns object, known to cause error with React select elements

obj.values() // returns array

When requiring Object patches individually you must first require object/rearmed. Example:

require('rearmed-js/object/rearmed');
require('rearmed-js/object/select');
require('rearmed-js/object/reject');

The following methods are used under the hood to provide patches to Object. I have exposed these methods publicly so that you can add your own custom methods to rearmed() objects. These methods are available on Object after requiring either of these: rearmed-js/object/rearmed or rearmed-js

Object.rearmed.add({
  myMethodName: function(){
    // add new method to rearmed() objects
  }
);

Object.rearmed.remove(
  myMethodName: function(){
    // remove method from rearmed() objects
  }
);

Number

var num = 8.5;

num.ceil() // returns number

num.floor() // returns number

num.isDecimal() // returns bool

num.isEven() // returns bool

num.isInteger() // returns bool

num.isOdd() // returns bool

num.round() // returns number

String

var str = 'Hello World':

str.capitalize() // returns string

str.caseCmp(str) // returns bool

str.chars() // returns array

str.downcase() // returns string

str.empty() // returns bool

str.endsWith(val) // returns bool

str.excludes(val, fromIndex=0) // returns bool

str.gsub(str, toStr) // returns string

str.includes(val, fromIndex=0) // returns bool

str.lstrip() // returns string

str.reverse() // returns string

str.rstrip() // returns string

str.startsWith(val) // returns bool

str.strip() // returns string

str.sub(str, toStr) // returns string
// Warning: doesn't warn when it overwrites the original sub method as it has been removed from the JS standard.

str.titleize(onlyFirstLetters=true) // returns string

str.toBool() // returns bool

str.upcase() // returns string

Browser / NodeJS / Typescript Support

  • Browser support is IE 9+ and everything else. Use the files in the dist folder if you need pre-minified files.
  • Array find doesnt work properly in old NodeJS 0.x and iojs.
  • String empty doesnt work properly in old NodeJS 0.x.
  • Typescript is supported however it does not support Class methods because its not possible to define static methods on existing interfaces such as Array. At this time the only effected method is Array.range

Contributing

  • I recommend discussing your intentions via an issue before making a PR because there are very concious design choices that must go into this library.
  • Only edit js files from src/ and test/ folders.
  • Use the gulp task: gulp to run the build after making your changes.
  • PR's should include tests. Testing these methods are simple & easy, check the test folder to see how it works.

Credits

Created by Weston Ganger - @westonganger

Similar Libraries Created By Me

More Repositories

1

spreadsheet_architect

Spreadsheet Architect is a library that allows you to create XLSX, ODS, or CSV spreadsheets super easily from ActiveRecord relations, plain Ruby objects, or tabular data.
Ruby
1,298
star
2

rails_i18n_manager

Web interface to manage i18n translations helping to facilitate the editors of your translations. Provides a low-tech and complete workflow for importing, translating, and exporting your I18n translation files. Designed to allow you to keep the translation files inside your projects git repository where they should be.
Ruby
205
star
3

paper_trail-association_tracking

Plugin for the PaperTrail gem to track and reify associations
Ruby
118
star
4

active_snapshot

Simplified snapshots and restoration for ActiveRecord models and associations with a transparent white-box implementation
Ruby
96
star
5

rodf

ODF generation library for Ruby
Ruby
53
star
6

protected_attributes_continued

The community continued version of protected_attributes for Rails 5+
Ruby
45
star
7

rearmed-rb

A collection of helpful methods and monkey patches for Arrays, Hash, Enumerables, Strings, Objects & Dates in Ruby
Ruby
41
star
8

sexy_form.rb

Dead simple HTML form field builder for Ruby with built-in support for many popular UI libraries such as Bootstrap
Ruby
38
star
9

rearmed_rails

A collection of helpful methods and monkey patches for Rails
Ruby
33
star
10

form_builder.cr

Dead simple HTML form builder for Crystal with built-in support for many popular UI libraries such as Bootstrap
Crystal
31
star
11

bootstrap-directional-buttons

Directional / Arrow buttons for Bootstrap
HTML
22
star
12

capistrano-precompile-chooser

Capistrano plugin to precompile your Rails assets locally, remotely, or not at all provided with a very convenient default terminal prompt.
Ruby
13
star
13

active_sort_order

The "easy-peasy" dynamic sorting pattern for ActiveRecord that your Rails apps deserve
Ruby
13
star
14

input-autogrow

jQuery plugin for autogrowing inputs
JavaScript
8
star
15

chosen-bootstrap-theme

A Bootstrap theme for Chosen Select that actually looks like Bootstrap
CSS
8
star
16

js-try

JS-Try is a Javascript implementation of the try method from Rails for safe navigation
JavaScript
6
star
17

chosen-material-theme

A Material theme for Chosen Select
CSS
6
star
18

search_architect

Dead simple, powerful and fully customizable searching for your Rails or ActiveRecord models and associations.
Ruby
6
star
19

rails_uuid_to_integer_primary_keys

A Rails Migration to convert your UUID primary keys back to integer / bigint primary keys
Ruby
5
star
20

pairer

Pairer is Rails app/engine to Easily rotate and keep track of working pairs
Ruby
5
star
21

chosen-remote-source

Provides remote data source support for chosen-js selects
JavaScript
4
star
22

input-case-enforcer

Enforce uppercase, lowercase, or Capitalized inputs & textareas
JavaScript
4
star
23

paperclip_utils

Collection of Paperclip processors and a Helper class for easier dynamic processors and styles on your Paperclip uploads
Ruby
4
star
24

active_record_simple_execute

Sanitize and Execute your raw SQL queries in ActiveRecord and Rails with a much more intuitive and shortened syntax
Ruby
4
star
25

active_record_case_insensitive_finders

Adds case-insensitive finder methods to Rails and ActiveRecord
Ruby
3
star
26

chosen-readonly

Readonly support for Chosen selects
JavaScript
3
star
27

better_exception_notifier

An exception notifier for Rails and Rack apps
Ruby
3
star
28

rails_nestable_layouts

Rails Nestable Layouts - Dead simple nested layouts for Rails
Ruby
3
star
29

accepts_nested_attributes_for_public_id

A patch for Rails to support using a public ID column instead of ID for use with accepts_nested_attributes_for
Ruby
2
star
30

minitest_change_assertions

Provides assertions for your Minitest suite to determine if an object has been changed
Ruby
2
star
31

common_website_scripts_and_styles

JavaScript
2
star
32

rails_template

Efficient Rails Template
Ruby
2
star
33

rearmed-css

CSS Utility Classes
CSS
2
star
34

basic_ruby_and_rails_style_guide

2
star
35

simple_assets

Dead simple HTML-based assets helper for Ruby. The main idea here is to promote re-usability for projects.
Ruby
2
star
36

active_record_alias_join

Easily add custom SQL table aliases for your joins and includes
2
star
37

github_activity_scraper.rb

Scrape your entire GitHub activity information for all-time. Helps for aggregating how much open source sh!t you get done.
Ruby
2
star
38

devise_whos_here

Devise extension for logging current active users logged in using only the fast Rails cache and not your database
Ruby
2
star
39

github_actions_ci_example

Ruby
1
star
40

jekyll_template

CSS
1
star
41

rubocop_template_for_productive_teams

Rubocop template designed speed up your teams development process instead of dragging it down
Ruby
1
star
42

rails_upgrade

Ruby
1
star
43

ruby_view_template_converters

Complete solutions to convert ERB, SLIM, AND HAML with the least amount of manual effort
Ruby
1
star
44

westonganger

1
star
45

no_bullshit_middleman_template

Template for efficient static website generation using Middleman
HTML
1
star
46

prawn_invoice

Dead simple Prawn based PDF invoice generator with support for custom invoice templates
Ruby
1
star
47

rails_dummy_app

Rails Dummy App and test_helper.rb for testing gems
Ruby
1
star
48

wagon_starter

Starter Template for LocomotiveCMS Wagon Sites
JavaScript
1
star
49

essential_capybara_helpers

A set of essential capybara helpers for everyday use
1
star
50

fast_try

FastTry is a simple method wrapper to the safe navigation operator in Ruby
Ruby
1
star
51

lazy_serialize

Lazy Serialize is an alternative to ActiveRecord's serialize method which does not serialize each column until the first call to the attribute.
Ruby
1
star
52

prawn_resume

Dead simple Prawn based PDF resume generator with support for custom resume templates
Ruby
1
star
53

automatic_rails_route_testing

Template for easy exception testing for all routes within a Rails app
Ruby
1
star
54

select-sync

Javascript plugin for HTML `select` elements to synchronize by selected or disabled options
JavaScript
1
star
55

rails_scrabble_with_friends

Simple web-based scrabble for you and your friends with zero friction authentication
Ruby
1
star
56

facebook_marketplace_scraper

A locally run Rails app to automatically search facebook marketplace for deals and aggregate them all in a list.
Ruby
1
star
57

wagon_kitchen_sink

Example website for LocomotiveCMS / Wagon
JavaScript
1
star
58

rails_clientside_javascript_error_handler

Easily handle client-side Javascript exceptions within your Rails app
Ruby
1
star
59

rails_custom_form_builder

A good example/starter pack for a custom form builder for use with Rails form_for
Ruby
1
star