Glock Blog

toCSV

Oct 1st, 2020Updated: less than 20 seconds ago
const toCSV = (arr, delimiter = ",") =>
  arr.map((v) => v.map((x) => x).join(delimiter)).join("\n");

toCSV([
  ["Name", "Email"],
  ["Jane Doe", "jane.doe@email.com"],
]); // Name,Email\nJane Doe,jane.doe@email.com

.replaceAll

Sep 30th, 2020Updated: less than 20 seconds ago
const queryString = "q=sample+query+params";
// old way
queryString.replace(/\+/g, " ");
// new way
queryString.replaceAll("+", " ");

display-mode: fullscreen

Sep 29th, 2020Updated: less than 20 seconds ago
@media all and (display-mode: fullscreen) {
  body {
    background-color: blue;
  }
}

npm link

Sep 28th, 2020Updated: less than 20 seconds ago
# local npm module
cd ~/local-dependency
npm link
# local project that uses your local npm module
cd ~/my-app
npm link local-dependency

React Custom Hook: useLocalStorage

Sep 25th, 2020Updated: less than 20 seconds ago
import { useState, useEffect } from "react";

export default function useLocalStorage(defaultValue, key) {
  const getItem = () => {
    const item = window.localStorage.getItem(key);

    const parsedItem = item !== null ? JSON.parse(item) : defaultValue;

    return {
      ...defaultValue,
      ...parsedItem,
    };
  };

  const [value, setValue] = useState(() => {
    return getItem();
  });

  useEffect(() => {
    const item = getItem();
    const valueToSet = { ...item, ...value };
    window.localStorage.setItem(key, JSON.stringify(valueToSet));
  }, [key, value]);

  return [value, setValue];
}

// example usage
function App() {
  const [preferences, setPreferences] = useLocalStorage({}, "preferences");

  const handleSelection = (e) => {
    const { name, value } = e.target;
    setPreferences({ ...preferences, name: value });
  };

  return (
    <div>
      <label htmlFor="mode">Mode</label>
      <select name="mode" onChange={handleSelection}>
        <option value="dark">Dark</option>
        <option value="light">Light</option>
      </select>
    </div>
  );
}

Is Whole Number

Sep 24th, 2020Updated: less than 20 seconds ago
const isWholeNumber = (n) => n - Math.floor(n) === 0;

React Custom Hook: useWindowSize

Sep 22nd, 2020Updated: less than 20 seconds ago
import { useState, useEffect } from 'react';

export default function useWindowSize() {
  const isClient = typeof window === 'object';
  const [windowSize, setWindowSize] = useState({
    height: undefined,
    width: undefined,
  });

  useEffect(() => {
    if (!isClient) return undefined;

    function handleResize() {
      setWindowSize({
        height: window.innerHeight,
        width: window.innerWidth,
      });
    }

    window.addEventListener('resize', handleResize);

    // initial window size
    handleResize();

    return () => window.removeEventListener('resize', handleResize);

  return windowSize;
}

// example usage
function App() {
  const size = useWindowSize();

  return (
    <div>{size.width}px / {size.height}px</div>
  )
}

Pass .env to Node Script

Sep 21st, 2020Updated: less than 20 seconds ago
export $(grep -v '^#' .env | xargs) && # ex. node index.js

Convert Truthy or Falsy to Boolean

Sep 18th, 2020Updated: less than 20 seconds ago
export default function App() {
  const arr = [];

  return (
    <div>
      {arr.length && <span>You won't see me but you will see a 0</span>}
      {/* make arr.length a boolean by adding !! */}
      {!!arr.length && <span>You won't see me and the 0 is gone</span>}
    </div>
  );
}

Global NPM and Yarn Packages

Sep 17th, 2020Updated: less than 20 seconds ago
npm list -g --depth 0
# or
yarn global list --depth=0

Array Difference

Sep 16th, 2020Updated: less than 20 seconds ago
function diff(a, b) {
  if (a.length > b.length) {
    return a.filter((a) => !b.includes(a));
  }
  return b.filter((b) => !a.includes(b));
}

diff([0, 2, 4], [1, 2, 3, 4]);

Docker Redis

Sep 14th, 2020Updated: less than 20 seconds ago
docker run --name my-redis-container -p 6379:6379 -d redis

JavaScript Case Conversion

Aug 24th, 2020Updated: less than 20 seconds ago
const uppercaseStr = "Testing";
const lowercaseStr =
  uppercaseStr.charAt(0).toLowerCase() + uppercaseStr.slice(1);
const lowercaseStr = "testing";
const uppercaseStr =
  lowercaseStr.charAt(0).toUpperCase() + lowercaseStr.slice(1);

console.log(console)

Jun 8th, 2020Updated: less than 20 seconds ago
// input
console.log(console);
// output
/*
{
  debug: [Function: debug],
  error: [Function: error],
  info: [Function: info],
  log: [Function],
  warn: [Function: warn],
  dir: [Function: dir],
  dirxml: [Function: dirxml],
  table: [Function: table],
  trace: [Function: trace],
  group: [Function: group],
  groupCollapsed: [Function: groupCollapsed],
  groupEnd: [Function: groupEnd],
  clear: [Function: clear],
  count: [Function: count],
  countReset: [Function: countReset],
  assert: [Function: assert],
  profile: [Function: profile],
  profileEnd: [Function: profileEnd],
  time: [Function: time],
  timeLog: [Function: timeLog],
  timeEnd: [Function: timeEnd],
  timeStamp: [Function: timeStamp],
  context: [Function: context],
  memory: [Getter/Setter]
}
*/