Skip to content

Instantly share code, notes, and snippets.

@jdgo-mars
Created February 14, 2019 21:44
Show Gist options
  • Save jdgo-mars/ac3c62c12e97e460c3b8920a8d8169cf to your computer and use it in GitHub Desktop.
Save jdgo-mars/ac3c62c12e97e460c3b8920a8d8169cf to your computer and use it in GitHub Desktop.
import { insert } from './insert';
const input = [
{
priority: 20
}
];
test('Should return array with one element when empty', () => {
const result = insert([], { priority: 2 }, 'priority');
expect(result).toEqual([{ priority: 2 }]);
});
test('Should add one element everytime its called', () => {
let result = insert([], { priority: 10 }, 'priority');
expect(result.length).toBe(1);
result = insert(result, { priority: 5 }, 'priority');
expect(result.length).toBe(2);
result = insert(result, { priority: 0 }, 'priority');
expect(result.length).toBe(3);
result = insert(result, { priority: 20 }, 'priority');
expect(result.length).toBe(4);
});
test('Should return array ordered by property', () => {
let result = insert(input, { priority: 40 }, 'priority');
expect(result).toEqual([{ priority: 40 }, ...input]);
result = insert(input, { priority: 0 }, 'priority');
expect(result).toEqual([...input, { priority: 0 }]);
result = insert(input, { priority: 0 }, 'priority');
expect(result).toEqual([...input, { priority: 0 }]);
});
test('Should add element at the start if priority is higher', () => {
let result = insert(input, { priority: 21 }, 'priority');
expect(result).toEqual([{ priority: 21 }, ...input]);
});
test('Should add element at the end if priority is lower', () => {
let result = insert(input, { priority: 5 }, 'priority');
expect(result).toEqual([...input, { priority: 5 }]);
});
/**
* Take a List of Objects and insert at
* the desired index based on the property
* @param array arr
* @param Object valToInsert
* @param string {property} Object property
* @returns {}
*/
export const insert = <T>(arr: Array<T>, valToInsert: T, property: string): Array<T> => {
let result: Array<T> = new Array(...arr) || [];
if (arr.length === 0) return [valToInsert];
for (let i = 0; i < arr.length; i++) {
if (valToInsert[property] >= arr[i][property]) {
result.splice(i, 0, valToInsert);
break;
}
if (valToInsert[property] < arr[i][property] && i + 1 === arr.length) {
result.push(valToInsert);
break;
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment