Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const array = [];
- for (let i = 0; i < 1E7; ++i)
- array.push(i);
- /* Set-based.
- */
- const optionA = () => [...new Set(array)];
- /* Push to new array, O(1) membership tests.
- */
- const optionB = () => {
- const unique = [];
- const inUnique = {};
- for (let i = 0; i < array. length; ++i) {
- const el = array[i];
- if (inUnique[el] !== true) {
- unique.push(el);
- inUnique[el] = true;
- }
- }
- return unique;
- };
- /* Push to new array, O(n) membership tests.
- * (Will be way too slow for large, unrestricted arrays)
- */
- const optionC = () => {
- const unique = [];
- for (let i = 0; i < array. length; ++i) {
- const el = array[i];
- if (unique.indexOf(el) === -1)
- unique.push(el);
- }
- return unique;
- };
- const benchmark = f => {
- console.log(f);
- for (let i = 0; i < 5; ++i) {
- const tPreMs = Date.now();
- f();
- const tSpentMs = Math.round(Date.now() - tPreMs);
- console.log(tSpentMs);
- }
- console.log();
- };
- benchmark(optionA);
- benchmark(optionB);
- benchmark(optionC);
Add Comment
Please, Sign In to add comment