JSFiddle - React, Tailwind, and code Playground
by Alex Alex
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.18.0/qunit.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.18.0/qunit.min.js"></script>
<div id='qunit'></div>
<div id='qunit-fixture'></div>
Babel + JSX
/*
The task:
Write a function that accepts 2 arrays. The arrays contain numbers and each input array is already sorted in increasing order. The function should create and return another array which contains all of the numbers that are in the 2 input arrays. The numbers in the returned array should also be sorted in increasing order. The goal is to write code that executes as fast as possible for large arrays. Implement without using any third party libraries.
For example if the input arrays are [1,2,5] and [2,3] then the result should be [1,2,2,3,5]
Describe and explain your implementation in a few words.
Feel free to ask any questions you have about the task.
*/
function sortConcat(arr1, arr2) {
let arr1Length = arr1.length;
let arr2Length = arr2.length;
let targetArr = arr1Length > arr2Length ? arr1 : arr2;
let srcArr = arr1Length > arr2Length ? arr2 : arr1;
let targetArrLength = targetArr === arr1 ? arr1Length : arr2Length;
let srcArrLength = srcArr === arr1 ? arr1Length : arr2Length;
let i = 0;
let j = 0;
// Check if arrays do not cross
if (targetArr[targetArrLength - 1] <= srcArr[0]) {
return targetArr.concat(srcArr);
} else if (srcArr[srcArrLength - 1] <= targetArr[0]) {
return srcArr.concat(targetArr);
}
// Other cases
while (j < srcArrLength) {
if (targetArr[i] >= srcArr[j]) {
targetArr.splice(i, 1, srcArr[j], targetArr[i]);
j++;
i = i + 2;
} else {
i++;
}
}
return targetArr;
}
// Let's check it
QUnit.test('Pass [1,2,5] and [2,3]', function simpleCheck(assert) {
var value = sortConcat([1,2,5], [2,3]).join(',');
assert.equal(value, '1,2,2,3,5', 'We expect value it will return the array [1,2,2,3,5]');
});
QUnit.test('Pass [-1,1,2,3,5,10,22] and [-20,28,36]', function middleheck(assert) {
var value = sortConcat([1,2,5], [2,3]).join(',');
assert.equal(value, '1,2,2,3,5',...