Skip to content

Instantly share code, notes, and snippets.

@mallond
Last active August 29, 2015 14:13
Show Gist options
  • Save mallond/914666d2c87ef7ca7303 to your computer and use it in GitHub Desktop.
Save mallond/914666d2c87ef7ca7303 to your computer and use it in GitHub Desktop.
Test code snippets - Javascript
//test Oject
var linkedList = { 'next': { 'next': { 'next': [Object], value: 1 }, value: 1 },
value: 1 };
// o = object
// func = function
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i],func);
}
}
}
//called with every property and it's value
function process(key,value) {
console.log(key + " : "+value);
}
//that's all... no magic, no bloated framework
traverse(linkedList,process);
//Time Complexity
function solution(int x, int y, int d)
{
assert(x < y); // 1
assert(d > 0);
int distance = y - x; // 2
int steps = distance / d; // 3
if(distance % d != 0) // 4
++steps;
return steps;
}
//Time Complexity
function solution(A) {
// write your code in JavaScript (ECMA-262, 5th edition)
result = 0;
if (!A || A.length == 0) return result;
np1 = A.length + 1;
sum = np1 * (1 + np1) / 2;
sumOfA = A.reduce(function(prev, current) {
return prev + current;
});
result = sum - sumOfA;
return result;
}
//Time Complexity
function solution(A) {
var i, ll = A.length, tot = 0, upto = 0, min = 9999;
for (i=0; i<ll; i++) tot += A[i];
for (i=0; i<ll-1; i++)
{
upto += A[i];
var a1 = upto, a2 = tot - a1, dif = Math.abs(a1 - a2);
if (dif < min)
min = dif;
}
return min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment