Prototype Methods

886 0 0 0

Last Updated : 2024-05-01 20:53:07

If you need to use the prototype to add new general methods to any general protoype or construct functions such as Object, Array, String .. etc, here are few examples


  1. Object:

  2. Arrays:

    1. Get Min Max values of any array
      Array.prototype.getMinMaxVals = function() {
      var t0 = performance.now()

      const min= Math.min(...this);
      const max= Math.max(...this);

      /*
      const min = this.reduce((prevValue, currentValue)=>{
      return (currentValue < prevValue) ? currentValue : prevValue ;
      })

      const max = this.reduce((prevValue2, currentValue2)=>{
      return (currentValue2 > prevValue2) ? currentValue2 : prevValue2 ;
      }) */

      var t1 = performance.now()
      console.log("This process took " + (t1 - t0) + " milliseconds.")

      return {
      min: min,
      max: max,
      }

      /*
      return {
      min: Math.min(...this),
      max: Math.max(...this),
      }
      */

      }

      const grades = [10, 7, 25, 2, 105, 0.7, 300, 2150, 410];
      console.log(grades.getMinMaxVals());
      //Bets choice is to use the Math.min and Math.max?

      Mohammed Anwar

      Mohammed Anwar

      Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .