Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Frontend Utility Functions and Advanced JavaScript Techniques

Tech 1

1. Utility Functions

Convert File to Base64

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    let result = '';
    fileReader.readAsDataURL(file);
    fileReader.onload = () => {
      result = fileReader.result;
    };
    fileReader.onerror = (error) => {
      reject(error);
    };
    fileReader.onloadend = () => {
      resolve(result);
    };
  });
}

Debounce Implementation

Debounce limits how often a function executes, running only after a period of inactivity (e.g., for search inputs):

let searchTimer;
function debounceSearch() {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    // Search logic here
  }, 300);
}

const searchInput = document.getElementById('search-input');
searchInput.addEventListener('input', debounceSearch);

Prevent Multiple Clicks

function preventMultipleClicks(method, args) {
  let context = this;
  if (!context.isClickAllowed) {
    context.isClickAllowed = false;
    method.apply(context, args || []);
    setTimeout(() => {
      context.isClickAllowed = true;
    }, 1500);
  } else {
    alert("Avoid repeated clicks!");
  }
}

export default {
  preventMultipleClicks,
};

Throttle Implementation

Throttle ensures a function runs at a fixed interval (e.g., with lodash.throttle):

const throttledSearch = _.throttle(() => {
  // Search logic here
}, 300);

searchInput.addEventListener('input', throttledSearch);

2. Common Problem Solutions

Manage and Cancel Pending Requests

Use AbortController to cancel fetch requests:

let abortController = new AbortController();

function fetchSearchResults() {
  abortController.abort();
  abortController = new AbortController();

  fetch('/search', { signal: abortController.signal })
    .then(res => res.json())
    .then(data => {
      // Handle results
    });
}

Fix AbortController Re-request Issue

Reset the controller to allow new requests:

<script>
  const btn1 = document.getElementById('btn1');
  const btn2 = document.getElementById('btn2');
  let controller = null;

  btn1.onclick = () => {
    controller = controller ? null : new AbortController();
    axios({
      url: 'http://localhost:5000/test1',
      params: { delay: 3000 },
      signal: controller?.signal
    })
    .then(res => console.log(res.data))
    .catch(err => console.log(err));
  };

  btn2.onclick = () => {
    controller?.abort('Request canceled');
  };
</script>

3. ES6 Array Operations

(I) Array Creation

// Constructor
const arr1 = new Array();
const arr2 = new Array(5); // Length 5
const arr3 = new Array('a', 'b', 'c');

// Literal
const arr4 = [];
const arr5 = [1, 2, 3];

(II) Array Properties

const arr = [1, 2, 3];
console.log(arr.constructor); // Array
console.log(arr.length);      // 3

(III) Check if Array

// Native method
const isArray = Array.isArray([1, 2, 3]); // true

// Polyfill
function isArray(arg) {
  return Object.prototype.toString.call(arg) === '[object Array]';
}

(IV) Add/Remove Elements

const arr = [1, 2, 3];

// Push (add to end)
arr.push(4, 5); // [1,2,3,4,5] (returns 5)

// Pop (remove from end)
const last = arr.pop(); // 5 (arr: [1,2,3,4])

// Shift (remove from start)
const first = arr.shift(); // 1 (arr: [2,3,4])

// Unshift (add to start)
arr.unshift(0); // [0,2,3,4] (returns 4)

// Splice (add/remove at index)
const removed = arr.splice(1, 1, 'a'); // arr: [0, 'a', 3, 4], removed: [2]

(V) Array ↔ String Conversion

// Array to string
const arr = [1, 2, 3];
const str = arr.join(','); // "1,2,3"

// String to array
const str = "a,b,c";
const arr = str.split(','); // ['a', 'b', 'c']

(VI) Slice and Concatenate

// Slice (new array)
const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3); // [2, 3]

// Concat (merge arrays)
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2); // [1,2,3,4]

(VII) Sort and Reverse

// Sort (ascending)
const arr = [3, 1, 2];
arr.sort((a, b) => a - b); // [1,2,3]

// Reverse
const reversed = arr.reverse(); // [3,2,1]

(VIII) Find Elements

// indexOf / lastIndexOf
const arr = [2, 9, 7, 8, 9];
console.log(arr.indexOf(9));       // 1
console.log(arr.lastIndexOf(9));   // 4

// find / findIndex
const found = arr.find(n => n > 5); // 9
const index = arr.findIndex(n => n > 5); // 1

(IX) Iterate Over Arrays

// map (transform)
const arr = [1, 2, 3];
const mapped = arr.map(x => x * 2); // [2,4,6]

// filter (select)
const filtered = arr.filter(x => x > 1); // [2,3]

// reduce (accumulate)
const sum = arr.reduce((acc, val) => acc + val, 0); // 6

(X) Other Methods

// Array.from (iterable to array)
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.from(arrayLike); // ['a', 'b']

// Array.of (values to array)
const arr = Array.of(1, 2, 3); // [1,2,3]

4. Merge Arrays in JavaScript

1. concat()

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2); // [1,2,3,4]

2. Spread Operator

const merged = [...arr1, ...arr2]; // [1,2,3,4]

3. push()

arr2.push(...arr1); // arr2: [3,4,1,2]

4. unshift()

arr2.unshift(...arr1); // arr2: [1,2,3,4]

5. splice()

arr2.splice(1, 0, ...arr1); // arr2: [3,1,2,4]

6. Array.from() + concat()

const merged = Array.from(arr1).concat(Array.from(arr2)); // [1,2,3,4]

7. reduce()

const merged = [arr1, arr2].reduce((acc, val) => acc.concat(val), []); // [1,2,3,4]

8. flat()

const arr1 = [1, [2, 3]];
const arr2 = [4, 5];
const merged = arr1.flat().concat(arr2); // [1,2,3,4,5]

5. Merge Objects in JavaScript

1. Object.assign()

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = Object.assign({}, obj1, obj2); // {a:1, b:2}

2. Spread Operator

const merged = { ...obj1, ...obj2 }; // {a:1, b:2}

3. Lodash merge()

const merged = _.merge(obj1, obj2); // {a:1, b:2}

4. Manual Merge (for...in)

const merged = {};
for (let key in obj1) merged[key] = obj1[key];
for (let key in obj2) merged[key] = obj2[key];

5. Merge Array Properties

const obj1 = { a: [1, 2] };
const obj2 = { a: [3, 4] };
const merged = { ...obj1, a: [...obj1.a, ...obj2.a] }; // {a: [1,2,3,4]}

6. ES6+ Set and Map

Set (Unique Collection)

// Create Set
const set = new Set([1, 2, 2, 3]); // {1,2,3}

// Add/Delete/Check
set.add(4);
set.delete(2);
set.has(3); // true
set.clear(); // Empty set

Map (Key-Value Collection)

// Create Map
const map = new Map([['a', 1], ['b', 2]]);

// Set/Get/Delete/Check
map.set('c', 3);
map.get('a'); // 1
map.delete('b');
map.has('c'); // true

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.