Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
ZacharyL2 / deep-clone.js
Last active April 11, 2022 10:11
Deep copy
const deepClone = (obj, map = new WeakMap()) => {
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (map.has(obj)) {
return map.get(obj);
}
const allDesc = Object.getOwnPropertyDescriptors(obj);
const cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);
@ZacharyL2
ZacharyL2 / interval-timer.js
Created February 16, 2022 09:13
A relatively accurate setInterval
function intervalTimer(callback, interval = 500) {
let counter = 1;
let timeoutId;
const startTime = Date.now();
function main() {
const nowTime = Date.now();
const nextTime = startTime + counter * interval;
timeoutId = setTimeout(main, interval - (nowTime - nextTime));
@ZacharyL2
ZacharyL2 / shallow-equal.js
Created February 27, 2022 04:12
shallowEqual in React
function shallowEqual(objA, objB) {
// P1
if (Object.is(objA, objB)) {
return true;
}
// P2
if (
typeof objA !== 'object' ||
objA === null ||
const deepEqual = (objA, objB, map = new WeakMap()) => {
// P1
if (Object.is(objA, objB)) return true;
// P2
if (objA instanceof Date && objB instanceof Date) {
return objA.getTime() === objB.getTime();
}
if (objA instanceof RegExp && objB instanceof RegExp) {
return objA.toString() === objB.toString();
@ZacharyL2
ZacharyL2 / flat.js
Last active March 3, 2022 06:36
Simulation of flat
const testArray = [1, [3, [4]], [3, [4, [5]]], [2, [3, [4, [5]]]], [2, [3, [4, [5]]]]];
function flatten(arr, depth = 1) {
if (depth <= 0) return arr;
return arr.flatMap((item) => {
if (Array.isArray(item) && item.some(Array.isArray)) {
return flatten(item, depth - 1);
}
return item;
// 👏 Solution 1
function unique(arr) {
const result = [];
for (const i of arr) {
let noRepeat = true;
for (const j of result) {
if (i === j) {
noRepeat = false;
{
// ✨ All types are assignable to `unknown`.
let unknownValue: unknown;
let neverValue: never;
let anyValue: any;
// ✅
unknownValue = 1;
unknownValue = '1';
unknownValue = {};
{
// ✨ In intersection types, all types will absorb `unknown`.
type T1 = unknown & null; // null
type T2 = unknown & number; // number
type T3 = unknown & never; // never
type T4 = unknown & unknown; // unknown
type T5<T> = T & unknown; // T
type T6 = unknown & any; // any
// never (`null & undefined` will become never)
{
// ✨ In union types, `unknown` absorbs all other types except `any`.
type T1 = unknown | null; // unknown
type T2 = unknown | number; // unknown
type T3 = unknown | never; // unknown
type T4 = unknown | unknown; // unknown
type T5<T> = T | unknown; // unknown
// ❗
type T6 = unknown | any; // any
{
type T1 = keyof unknown; // never
// `keyofStringsOnly: false` will return `string | number | symbol`
// `keyofStringsOnly: true` will return `string`
type T2 = keyof any;
}