Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Recursive algorithms


coputepower

Recursion


In this article
1- What is a Recursive function and the problem it solve?
2- Example Computing Powers .

Recursive function

A Recursive function is a function that calls itself ether directly or indirectly through another function .A Recursive function is called to solve a problem by solving a smaller instance of the same problem unless it is the simplest case(s) or so-called base case(s) it will return the result.


Example Computing Powers

1 - The simplest case when you want to compute x^n is when n = 0 the result always be 1 no matter what x is .

function CopmutePower(x , n){
 if (n == 0){
   return 1;
  }


}

2 - The second case we can think about is when n is positive

when you multiply powers of  x you add the exponents: x^a *  x^b =  x^(a+b)
 eg. 2^2 × 2^4 = 2^(2+4) = 64.

If n is positive and even then  x^​n ​​= x^(​n/2) ​​ * x^(​n/2)
 eg. 2^6 = 2^(6/2) * 2^(6/2) = 64   and for y= x^(n/2) Therefore x^n = y * y

function CopmutePower(x , n){
  // n = 0 Simplest case(base case)
 if (n == 0){
   return 1;
  }

  // n is positive even
  if (n % 2 == 0){
  var y = CopmutePower(x, n / 2);
  return y * y;
  }

}


3 -If n is positive and odd then x^​n ​​= x^(​n−1) ​​ * x  in this case if n-1 = 0 then it will be the base case when n = 0  and if n-1  is positive and even  then it will be the second case .
Therefor you could compute those cases recursively 

function CopmutePower(x , n){
  // n = 0 Simplest case(base case)
 if (n == 0){
   return 1;
  }

  // n is positive and even
  if (n % 2 == 0){
  var y = CopmutePower(x, n / 2);
  return y * y;
  }

   // n is positive and even
    if (!(n % 2 == 0)){
     return x * CopmutePower(x, n - 1);       
   }


}

4 - If n is negative then x^n = 1 / (x^n)


function CopmutePower(x , n){
  // n = 0 Simplest case(base case)
 if (n == 0){
   return 1;
  }

  // n is positive and even
  if (n % 2 == 0){
  var y = CopmutePower(x, n / 2);
  return y * y;
  }

   // n is positive and even
    if (!(n % 2 == 0)){
     return x * CopmutePower(x, n - 1);       
   }
 
     //  n is negative
    if (n < 0){
     return 1 / CopmutePower(x, -n);       
   }

}

-- JavaScript Code
See the Pen Recursive powers by Mohamed Salah (@saad306) on CodePen.

-- C# Code

Algorithm - Insertion Sort

In this article
What is an Insertion sort 
Implement Insertion sort - Demo (JavaScript - C#)

1 - 
What is an Insertion Sort


It is a sorting algorithm which sorts each Item in the list or array by shifting elements as they're encounter(one by one.)
In insertion sort we loop over an array from left to right and we compare current item in the iteration to it's left if it's less than pull it out and move the left index to the right then Insert current item to the sorted place . so everything left to the CurrentItem in the iteration Is sorted.

So let's see a sample implementation.

JavaScript .


See the Pen insertion sort by Mohamed Salah (@saad306) on CodePen.


C#



JavaScript Prototypes and Inheritance

In this article
what's JavaScript prototypes 
JavaScript Inheritance 

1 - What's JavaScript prototypes


JavaScript uses prototypes where many other object-oriented languages use classes for inheritance . It is possible to simulate many class-based features with prototypes in JavaScript .wikipedia
All JavaScript objects inherit the properties and methods from their prototype. Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype. Objects created with new Date() inherit the Date.prototype. The Object.prototype is on the top of the prototype chain.w3schools
You can consider a prototype is a pointer to a base Object when you create a new instance of that Object , and this mean if you change a prototype property of an object it will affect all objects constructed using that object.
So let's see example and Create a new object and a new instance of it.

Create object and new instance of it.
Note : that every constructed function has a property called __proto__ , and you can use it to access base object prototype property as shown below.
function employee(name, salary) {
    this.Name = name;
    this.salay = salary
}
//Create prototype transportAllowance property.
employee.prototype.transportAllowance = 500;
// new instance of employee
var emp = new employee('Ahmed', 5000);
// Create transportAllowance property of emp.
emp.transportAllowance = 400;
//
document.write(emp.transportAllowance + '<br/>'); //Output 400

document.write(emp.__proto__.transportAllowance + '<br/>'); //output 50

2 - JavaScript Inheritance


Inheritance is the ability to create a class from another class, the "parent" class, extending the functionality and state of the parent in the derived, or "child" class. It allows derived classes to overload methods from their parent class.
Inheritance is one of the pillars of object-orientation. It is the mechanism of designing one class from another and is one of the ideas for code reusability, supporting the concept of hierarchical classification. C# programs consist of classes, where new classes can either be created from scratch or by using some or all properties of an existing class.
Another feature related to inheritance and reusability of code is polymorphism, which permits the same method name to be used for different operations on different data types. Thus, C# supports code reusability by both features. wiki
JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in ES6, but is syntactical sugar, JavaScript remaining prototype-based).
When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. null, by definition, has no prototype, and acts as the final link in this prototype chain.
While this is often considered to be one of JavaScript's weaknesses, the prototypal inheritance model is in fact more powerful than the classic model. It is, for example, fairly trivial to build a classic model on top of a prototypal model, while the other way around is a far more difficult task. developer.mozilla
let's see example in how to apply inheritance in JavaScript.

Creating Prototypal Inheritance Chains
//use this as a base function
function Person(firstName, lastName) {
    this.FirstName = firstName,
    this.LastName = lastName,
     this.FullName = function () {
         return this.FirstName + ' ' + this.LastName
     }

}
//and this is a derived function that inherited from Person function above
function employee(firstName, lastName, department, salary) {
    //Call Person
    Person.call(this, firstName, lastName);
    this.Department = department,
    this.salay = salary,
    this.showInfo = function () {
        return 'Name: ' + this.FirstName + ' ' + this.LastName
          + '<br/>' + 'Department: ' + this.Department
          + '<br/>' + 'Salary: ' + this.salay
    };
}
//inherit Person
employee.prototype = Object.create(Person.prototype);
//set employee constructor to itself
employee.prototype.constructor = employee;
document.write(new employee('Ahmed', 'Saad', 'HR', '5000').showInfo())
//output
//Name: Ahmed Saad
//Department: HR

//Salary: 5000

JavaScript Properties

In this article
Bracket Notation for Properties 
Using Descriptors property 
Writable attribute 
Using Enumerabe Attribute 
Useing Configurable Attribute 
Using get and set 

1 - Bracket Notation for Properties


You can access property by using object followed by its property like this:
'use strict'
var employee = {

    name: 'Ahmed',
    salary: '5000'
}
// use object followed by property

document.write(employee.name) // output Ahmed

Or by using bracket notation like this:
'use strict'
var employee = {

    name: 'Ahmed',
    salary: '5000'
}
// bracket notation

document.write(employee['name']) // output Ahmed

Also you can define a new property like this:
'use strict'
var employee = {

    name: 'Ahmed',
    salary: '5000'
}
//assign new property
employee['lastName'] = 'Saad';
// bracket notation

document.write(employee['lastName']) // output Saad

2 - Using Descriptors property


Beside name and value every property has a property Descriptor.
Use property Descriptor to see attributes of that property.
Every property has attributes value , writable , enumerable and configurable attributes and by default it's all set to true.
You can see attributes by looping over Object.getOwnPropertyDescriptor() property like this:
'use strict'
var employee = {

    name: 'Ahmed',
    salary: '5000'
}
// looping over Object.getOwnPropertyDescriptor()
for (var property in Object.getOwnPropertyDescriptor(employee, 'name')) {
    document.write(property + ' ' + Object.getOwnPropertyDescriptor(employee, 'name')[property])
    document.write('<br/>')
}
//Output
//value Ahmed
//writable true
//enumerable true

//configurable true

3 - Writable attribute


You can use writable attribute to define whether the value of property can be changed from initial value or not.
You can change the value of writable attribute by using Object.defineProperty() like this :
'use strict'
var employee = {

    name: 'Ahmed',
    salary: '5000'
}
Object.defineProperty(employee, 'name', { writable: false });
//trying to alter name
employee['name'] = 'Saad'
document.write(employee['name']);
//Output
//If you go to developer tools in your browser you will see error like this
// " Uncaught TypeError: Cannot assign to read only property 'name' of #<Object> "

// Note : you have to use 'use strict'


You can not apply non-writable property if a property contains an object , you can use Object.freeze() instead like this :
'use strict'
var employee = {

    name: {
        firstName: 'Ahmed',
        lastName: 'Saad'
    },
    salary: '5000'
}
Object.defineProperty(employee, 'name', { writable: false });
//trying to alter name.lastName
employee.name.lastName = 'Salah'
document.write(employee.name.lastName); //Output Salah
Object.freeze(employee.name);
//trying to alter name.lastName
employee.name.lastName = 'Saad';
document.write(employee.name.lastName);
//Output
//If you go to developer tools in your browser you will see error like this
// "Uncaught TypeError: Cannot assign to read only property 'lastName' of #<Object> "

// Note : you have to use 'use strict'

4 - Using Enumerabe Attribute


You can prevent property from being looping by setting enumerable attribute to false like this:


Note : If you set enumerable attribute to false it will affect when you try to serialize object to JSON
'use strict'
var employee = {

    name: 'Ahmed',
    salary: '5000'
}
// looping over Object.getOwnPropertyDescriptor()
for (var property in employee) {
    document.write(property + ' ' + employee[property])
    document.write(' ')

//Output value Ahmed , salary 5000

//new line
document.write('<br/>')

Object.defineProperty(employee, 'name', { enumerable: false });
for (var property in employee) {
    document.write(property + ' ' + employee[property])


} //Output salary 5000

4 - Useing Configurable Attribute


Configurable Attribute can prevent an attribute from being changed or any property from being deleted from the object.
Use Object.defineProperty(Object, 'property' , {configurable : false}) to set value to false.

5 - Using get and set


You can use get and set to set or return value by using a function like this


'use strict'
var employee = {

    name: {
        firstName: 'Ahmed',
        lastName: 'Saad'
    },
    salary: '5000'
}
Object.defineProperty(employee, 'fullName', {
    get: function () {
        return this.name.firstName + ' ' + this.name.lastName
    }
});
document.write(employee.fullName) //output Ahmed Saad


// Note you can use same technique for set to set new value