Skip to content

Instantly share code, notes, and snippets.

@thecodeholic
Last active September 23, 2018 16:30
Show Gist options
  • Save thecodeholic/3b49b4e7e5a18f50d65c2deb4f03ce87 to your computer and use it in GitHub Desktop.
Save thecodeholic/3b49b4e7e5a18f50d65c2deb4f03ce87 to your computer and use it in GitHub Desktop.
JS prototype modification on Natives
Object.prototype.numberKeys = function(){
  // ...
};

Array.prototype.minElement = function(){
  // ...
};

String.prototype.wordCount = function(){
  // ...
};

var foo = {
  a: 'bar',
  b: 'foo',
  '1': 'bar2',
  '2': 'foo2'
};
foo.numberKeys(); // [1, 2]

var arr = [1, 2, 3, 0, 4];
arr.minElement(); // 0

var str = 'This is my long long string';
str.wordCount(); // 6

var students = [
  {
    id: 1,
    name: 'John',
    // ...
  },
  {
    id: 2,
    name: 'Kyle',
    // ...
  },
  // ...
];

// We need to find student by id
var myStudent = findById(students, 1);


function findById(students, id){
  // iterate over students and return found student
};

var myStudent = students.findById(1);

Array.prototype.findById = function(id){
  // iterate over **this** and return found student
};

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.toCamel = function () {
    return this.replace(/(\-[a-z])/g, function ($1) {
        return $1.toUpperCase().replace('-', '');
    });
};
String.prototype.toDash = function () {
    return this.replace(/([A-Z])/g, function ($1) {
        return "-" + $1.toLowerCase();
    });
};
Number.prototype.isBetween = function (num1, num2, including) {
    if (!including) {
        if (this.valueOf() < num2 && this.valueOf() > num1) {
            return true;
        }
    } else {
        if (this.valueOf() <= num2 && this.valueOf() >= num1) {
            return true;
        }
    }
    return false;
};

"this-is-my-long-method".toCamel(); // "thisIsMyLongMethod"
"thisIsMyLongMethod".toDash(); // "this-is-my-long-method"
"  this is string to be trimmed  ".trim(); // "this is string to be trimmed"

var n = 7;
n.isBetween(3, 7); // false;
n.isBetween(3, 8); // true;
n.isBetween(3, 7, true); // true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment