Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active January 30, 2017 17:15
Show Gist options
  • Save bradoyler/0e14ff07202dc923976c to your computer and use it in GitHub Desktop.
Save bradoyler/0e14ff07202dc923976c to your computer and use it in GitHub Desktop.
Data structures and algorithms using javascript. Computer science FTW.
var array = [0, 1, 2];
var weekDays = ['sun','mon','tues','wed','thurs','fri','sat'];
var str = "test";
var obj = {};
for (var i = 0; i < array.length; i++) {
var test = array[i];
}
//class
function MyFunc() {
return true;
}
MyFunc.prototype.isEnabled = true;
// string reverse
MyFunc.prototype.reverse = function(str) {
var arr = [];
var len = str.length;
for (var i = 0; i <= len; i++) {
arr.push(str.charAt(len - i))
}
return arr.join('');
}
MyFunc.prototype.reverse2 = function function(s){
return s.split('').reverse().join('');
}
// for...in
for (var variable in obj) {
if (obj.hasOwnProperty(variable)) {
}
}
// switch
switch (str) {
case 'test':
break;
default:
}
// sorting - based on quicksort http://en.cppreference.com/w/cpp/algorithm/qsort
// http://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/
var arr =["qwe","qwerty"]
arr.sort(function(a, b){
return b.length - a.length; // ASC -> a - b; DESC -> b - a
});
// array rotate
function rotate(arr, n) {
return arr.slice(n, arr.length).concat(arr.slice(0, n));
}
// stack LIFO (last in, first out)
var stack = [];
stack.push(2); // stack is now [2]
stack.push(5); // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i); // displays 5
// queue FIFO (first in, first out)
var queue = [];
queue.push(2); // queue is now [2]
queue.push(5); // queue is now [2, 5]
var i = queue.shift(); // queue is now [5] since shift removes from 'front' of array
alert(i); // displays 2
// Hashtables are js objects, silly
// constructing hashtable class
function HashTable(obj)
{
this.length = 0;
this.items = {};
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
this.items[p] = obj[p];
this.length++;
}
}
}
// usage:
var h = new HashTable({one: 1, two: 2, three: 3, "i'm no 4": 4});
// Map - returns a collection of headlines
var headlines = Array.prototype.slice.call(document.getElementsByTagName('h3'))
.map(function(node) {
return node.innerText;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment