JavaScript Samples
by KevinABoucher
HTML
JavaScript Samples
<div id="info"></div>
JavaScript
//////////////////////////////////////
// Max in Array
//////////////////////////////////////
function max(arr) {
var m;
for(var i=0; i < arr.length; i++)
{
if(i==0) {
m = arr[i];
continue;
}
if(arr[i] > m)
{
m = arr[i];
}
}
return m;
}
var myArray = [-1,-2,-3,100,5];
log("Max in Array");
log(max(myArray));
log("Max in Array with library");
log(Math.max.apply(null,myArray));
//////////////////////////////////////
// LINKED LIST
//////////////////////////////////////
function LinkedList() {}
LinkedList.prototype = {
length: 0,
head: null,
tail: null
};
LinkedList.Node = function(data) {
this.prev = null;
this.next = null;
this.data = data;
};
LinkedList.prototype.append = function(node) {
if (this.head === null) {
node.prev = null;
node.next = null;
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.prev = this.tail;
this.tail = node;
}
this.length++;
};
var myList = new LinkedList();
myList.append(new LinkedList.Node("a"));
myList.append(new LinkedList.Node("b"));
myList.append(new LinkedList.Node("c"));
log("Linked list");
var node = myList.head;
for(var i=0; i<myList.length; i++)
{
log(node.data);
node = node.next;
}
log("Linked list reveresed");
reverseLinkedList(myList);
var node1 = myList.head;
for(var i=0; i<myList.length; i++)
{
log(node1.data);
node1 = node1.next;
}
function reverseLinkedList (linkedList)
{
var temp = null;
var current = linkedList.head;
// swap next and prev for all nodes of doubly linked list
while (current != null)
{
current.prev = current.next;
current.next = temp;
temp = current;
current = current.prev;
}
linkedList.head = temp;
}
//////////////////////////////////////
// fibonacci - Fn = Fn-1 + Fn-2
//F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11
// 0 1 1 ...