DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
lionelrowe profile image
lionel-rowe

Here are a few of the more generally useful ones:

const isSameOrigin = (url: string) =>
    new URL(url, window.location.href).origin === window.location.origin

const isTouchDevice = window.matchMedia('(pointer: coarse)').matches
const isMobile = navigator.userAgent.includes('Mobi')

const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)

const decodeBase64 = (base64: string) =>
    new TextDecoder().decode(new Uint8Array(atob(base64).split('').map((char) => char.charCodeAt(0))))

const encodeBase64 = (str: string) =>
    btoa(Array.from(new TextEncoder().encode(str))
        .map((n) => String.fromCharCode(n))
        .join(''))

const xor = (...args: any[]) =>
    args.filter(Boolean).length === 1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Those are currently very useful ones!

I've a slightly different base64encode one

/**
 * encodes a file into base64
 * @param {import('fs').PathOrFileDescriptor} fileOrigin
 * @returns {string}
 */
function base64_encode(fileOrigin) {
  /** @type {Buffer} */
  const file = fs.readFileSync(fileOrigin);
  return Buffer.from(file).toString('base64');
}
Enter fullscreen mode Exit fullscreen mode

I'll check the differences later 😁

Collapse
 
brunnerlivio profile image
Livio Brunner • Edited

The base64 functions from @lionel-rowe are compatible with (most) browser. The fs module is only available in Node.js :)

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Of course but what I want to check is the details on what's happening on this TextDecoder(), it's decode method and also the reason for it to use an array of 8-bit unsigned integers 😂

Thread Thread
 
lionelrowe profile image
lionel-rowe

TextEncoder and TextDecoder convert strings to and from their equivalent UTF-8 bytes. So for example, new TextEncoder().encode('foo 福 🧧') gives Uint8Array [102, 111, 111, 32, 231, 166, 143, 32, 240, 159, 167, 167], where bytes 0..2 represent the 3 ASCII characters "foo", 4..6 represent the single 3-byte character "福", and 8..11 represent the single 4-byte character "🧧" (3 and 7 are spaces).

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Thanks you for the explanation! 😁