Skip to content

Latest commit

 

History

History
245 lines (194 loc) · 4.38 KB

File metadata and controls

245 lines (194 loc) · 4.38 KB

Basic Algorithm Scripting

  1. Basic Algorithm Scripting
  2. Object Oriented and Functional Programming

Basic Algorithm Scripting

Reverse

function reverseString(str) {
    return str;
}
reverseString("hello");
  • method 1:
  • split("")
  • reverse()
  • join("")
function reverseString(str) {
    return str.split("").reverse().join("");
}
reverseString("hello");

  • method 2:
function reverseString(str) {
    var newString = "";
    for (var i = str.length - 1; i >= 0; i--) {
        newString += str[i];
    }
    return newString;
}
reverseString('hello');

Recursion (递归)

5! = 1 * 2 * 3 * 4 * 5 = 120


function factorialize(num) {
  if (num === 0) {return 1;}
  return num * factorialize(num-1);
}

factorialize(5);

Check for Palindromes

  • /[^A-Za-z0–9]/g or /[\W_]/g
  • toLowerCase()
  • replace()
function palindrome(str) {
  // Good luck!
  var re = /[\W_]/g;
  var lowRegStr = str.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join('');
  return reverseStr === lowRegStr;
}

palindrome("eye");
function palindrome(str) {
 var re = /[^A-Za-z0-9]/g;
 str = str.toLowerCase().replace(re, '');
 var len = str.length;
 for (var i = 0; i < len/2; i++) {
   if (str[i] !== str[len - 1 - i]) {
       return false;
   }
 }
 return true;
}
palindrome("A man, a plan, a canal. Panama");

Find the Longest Word in a String


Object Oriented and Functional Programming

Declare JavaScript Objects as Variables

var car = {
  "wheels":4,
  "engines":1,
  "seats":5
};

var motorBike = {
// Only change code below this line.
  "wheels":23,
  "engines":2,
  "seats":3
};

Construct JavaScript Objects with Functions

var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 5;
};

// Only change code below this line.
  var MotorBike = function() {
  this.wheels = 2;
  this.engines = 1;
  this.seats = 2;
};

Make Instances of Objects with a Constructor Function

var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 5;
};

// Only change code below this line.
var myCar = new Car();
myCar.nickname = "twin";

Make Unique Objects by Passing Parameters to our Constructor

var Car = function(wheels,seats,engines) {
  //Change this constructor
  this.wheels = wheels;
  this.seats = seats;
  this.engines = engines;
};

//Try it out here
var myCar = new Car(2,3,5);

Make Object Properties Private


Iterate over Arrays with .map


Condense arrays with .reduce


Filter Arrays with .filter


Sort Arrays with .sort


Reverse Arrays with .reverse


Concatenate Arrays with .concat


Split Strings with .split


Join Strings with .join