Skip to content

Instantly share code, notes, and snippets.

@mefernandez
Created December 27, 2013 17:29
Show Gist options
  • Save mefernandez/8149971 to your computer and use it in GitHub Desktop.
Save mefernandez/8149971 to your computer and use it in GitHub Desktop.
Now it's me.
describe('A function',function(){
it('extracts the simmetric difference of two arrays of integers',function(){
expect(diff([1,2,3], [4,5,6])).toEqual([1,2,3,4,5,6]);
expect(diff([1,2,3], [1,2,3])).toEqual([]);
expect(diff([1], [])).toEqual([1]);
expect(diff([1], [2])).toEqual([1,2]);
expect(diff([1,2,3], [1,2,3,4])).toEqual([4]);
});
it('checks if integers in an array are ordered',function(){
expect(isOrdered([1,2,3,4,5,6])).toBe(true);
expect(isOrdered([1])).toBe(true);
expect(isOrdered([1,2])).toBe(true);
expect(isOrdered([1,2,2])).toBe(true);
expect(isOrdered([1,2,2,3])).toBe(true);
expect(isOrdered([1,2,3,4,5,6].reverse())).toBe(true);
expect(isOrdered([1].reverse())).toBe(true);
expect(isOrdered([1,2].reverse())).toBe(true);
expect(isOrdered([1,2,2].reverse())).toBe(true);
expect(isOrdered([1,2,2,3].reverse())).toBe(true);
expect(isOrdered([1,2,1])).toBe(false);
expect(isOrdered([3,2,1,2])).toBe(false);
});
});
function diff(a, b) {
var c = a.concat(b).sort();
var d = [];
if (c.length === 0)
return d;
if (c.length == 1)
return c;
// Check for the first element
if (c[0] < c[1])
d.push(c[0]);
if (c.length > 2) {
// A number is unique if it's different from prev and next
for (var i=1; i<c.length-1; i++) {
if ((c[i-1] < c[i]) && (c[i] < c[i+1])) {
d.push(c[i]);
}
}
}
// Check the last element
if (c[c.length-2] < c[c.length-1])
d.push(c[c.length-1]);
return d;
}
function isOrdered(a) {
if (a.length < 2)
return true;
var m = 0;
for (var i=0; i<a.length-1; i++) {
var x = (a[i] - a[i+1]);
// If they're equal, loop to next element
if (x === 0)
continue;
// m=0, we don't know if it's ordered up or down
if (m === 0) {
if (x < 0)
m = -1;
else if (x > 0)
m = 1;
}
// Ok, check if it's ordered
if ((x*m) < 0)
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment