Skip to content

Instantly share code, notes, and snippets.

@radekstepan
Last active March 4, 2016 09:25
Show Gist options
  • Save radekstepan/3087319d623ac77de4af to your computer and use it in GitHub Desktop.
Save radekstepan/3087319d623ac77de4af to your computer and use it in GitHub Desktop.
Merge two sorted arrays into a sorted array of unique values from both
/node_modules
*.log
.DS_Store
language: node_js

#merge-arrays

Merge two sorted arrays into a sorted array of unique values from both.

$ nvm use
$ npm install
$ npm test
{
"concat": [
[ 17 ],
[ 2, 6, 8, 10 ],
[ 2, 6, 8, 10, 17 ]
],
"same": [
[ 1, 2, 3 ],
[ 1, 2, 3 ],
[ 1, 2, 3 ]
],
"empty": [
[ ],
[ 2, 6 ],
[ 2, 6 ]
],
"both-empty": [
[ ],
[ ],
[ ]
],
"t1": [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 1, 2, 3, 4, 5, 6 ]
],
"t2": [
[ 1, 11 ],
[ 2, 3, 10 ],
[ 1, 2, 3, 10, 11 ]
],
"t3": [
[ 2, 5, 6, 9 ],
[ 1, 2, 3, 29 ],
[ 1, 2, 3, 5, 6, 9, 29 ]
]
}
"use strict";
module.exports = (a, b) => {
let c = [],
i = 0,
j = 0,
last = null;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
if (a[i] != last) c.push(last = a[i]);
i++;
} else {
if (b[j] != last) c.push(last = b[j]);
j++;
}
}
return c.concat((i != a.length) ? (a[i] != last) ? a.slice(i) : [] : (b[j] != last) ? b.slice(j) : []);
};
{
"name": "merge-arrays",
"version": "1.0.0",
"author": "Radek Stepan <[email protected]>",
"main": "index.js",
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^2.4.5"
},
"scripts": {
"test": "./node_modules/.bin/mocha test.js --ui exports --bail --reporter spec"
}
}
"use strict";
let assert = require('chai').assert;
let lib = require('./index.js');
let fix = require('./fixtures.json');
for (let i in fix) {
exports[`test ${i}`] = (done) => {
assert.deepEqual(lib.apply(null, fix[i]), fix[i][2]);
done();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment