人妻夜夜爽天天爽三区丁香花-人妻夜夜爽天天爽三-人妻夜夜爽天天爽欧美色院-人妻夜夜爽天天爽免费视频-人妻夜夜爽天天爽-人妻夜夜爽天天

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

分享一些不錯的JS/TS代碼片段

admin
2025年1月24日 15:12 本文熱度 619

方法順序執行,不論同步還是異步

以下代碼實現方法順序執行,不論同步還是異步,

let result;
for (const f of [func1, func2, func3]) {
  result = await f(result);
}
/* use last result (i.e. result3) */

更老版本的寫法:

const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
  (...funcs) =>
  (x) =>
    funcs.reduce(applyAsync, Promise.resolve(x));

const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);

參考:MDN: 使用Promise[1]

閉包緩存計算結果,提高性能

function memoize(fn{
    const cache = {};

    return function(...args{
        const key = JSON.stringify(args);
        if (cache[key] !== undefined) {
            return cache[key];
        }
        const result = fn(...args);
        cache[key] = result;
        return result;
    };
}

function fibonacci(n{
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

const memoizedFibonacci = memoize(fibonacci);
console.log(memoizedFibonacci(10)); // 輸出 55
console.log(memoizedFibonacci(20)); // 輸出 6765

在這個例子中,memoize 函數通過閉包緩存了計算結果,提高了遞歸函數的性能。

閉包實現函數柯里化

通用的函數柯里化工具函數,注意這里沒有處理this的指向

function curry(fn{
  return function curried(...args{
    if (args.length >= fn.length) {
      return fn(...args);
    }
    return function (...nextArgs{
      return curried(...args, ...nextArgs);
    };
  };
}

function sum(a,b,c){
  return a+b+c;
}

const curriedSum = curry(sum);

console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(12)(3)); // 6
console.log(curriedSum(1)(23)); // 6

TypeScript

枚舉+位運算進行狀態判斷

枚舉+位運算進行狀態判斷與運算

enum AnimalFlags {
  None        = 0,
  HasClaws    = 1 << 0,
  CanFly      = 1 << 1
}

interface Animal {
  flags: AnimalFlags;
  [key: string]: any;
}

function printAnimalAbilities(animal: Animal{
  var animalFlags = animal.flags;
  if (animalFlags & AnimalFlags.HasClaws) {
    console.log('animal has claws');
  }
  if (animalFlags & AnimalFlags.CanFly) {
    console.log('animal can fly');
  }
  if (animalFlags == AnimalFlags.None) {
    console.log('nothing');
  }
}

var animal = { flags: AnimalFlags.None };
printAnimalAbilities(animal); // nothing
animal.flags |= AnimalFlags.HasClaws;
printAnimalAbilities(animal); // animal has claws
animal.flags &= ~AnimalFlags.HasClaws;
printAnimalAbilities(animal); // nothing
animal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;
printAnimalAbilities(animal); // animal has claws, animal can fly

Animal 有多種狀態時判斷、運算十分簡潔

假如讓我來寫的話,不用枚舉+位運算的話可能實現如下

type AnimalFlags = 'None' | 'HasClaws' | 'CanFly';
interface Animal {
  flags: AnimalFlags[];
  [key: string]: any;
}

function printAnimalAbilities(animal: Animal{
  var animalFlags = animal.flags;
  if (!animalFlags || animalFlags.includes('None')) {
    return 'nothing';
  }
  if (animalFlags.includes('HasClaws')) {
    console.log('animal has claws');
  }
  if (animalFlags.includes('CanFly')) {
    console.log('animal can fly');
  }
}

var animal: Animal = { flags: ['None'] };
printAnimalAbilities(animal); // nothing
animal.flags = ['HasClaws'];
printAnimalAbilities(animal); // animal has claws
animal.flags = ['None'];
printAnimalAbilities(animal); // nothing
animal.flags = ['HasClaws''CanFly'];
printAnimalAbilities(animal); // animal has claws, animal can fly

運算不太方便,比如狀態是['HasClaws', 'CanFly'], 想移除Fly狀態需要進行數組操作,比位運算麻煩許多

參考:深入理解 TypeScript:枚舉[2]

React 導出 useImperativeHandle 的聲明

定義:

type CountdownProps = {}
    
type CountdownHandle = {
  start: () => void,
}
    
const Countdown: React.ForwardRefRenderFunction<CountdownHandle, CountdownProps> = (
  props,
  forwardedRef,
) => {
  React.useImperativeHandle(forwardedRef, ()=>({
    start() {
      alert('Start');
    }
  }));

  return <div>Countdown</div>;
}

export default React.forwardRef(Countdown);

在上層組件中常想知道子組件useImperativeHandle的定義,可以這么寫:

const App: React.FC = () => {
  // 這個類型等于 `CountdownHandle`,但不需要手動 import CountdownHandle
  type CountDownRef = React.ElementRef<typeof Countdown>;

  const ref = React.useRef<CountDownRef>(null); // assign null makes it compatible with elements.

  return (
    <Countdown ref={ref} />
  );
};

CountDownRef這個類型等于 CountdownHandle,但不需要手動 import CountdownHandle

參考:stackoverflow[3]

+ -修飾符

+ -修飾符可以添加或去掉readonly 和 ?,如

type CreateMutable<Type> = {
  -readonly [Property in keyof Type]: Type[Property];
};
 
type LockedAccount = {
  readonly id: string;
  readonly name: string;
};
 
type UnlockedAccount = CreateMutable<LockedAccount>;

// UnlockedAccount 等效于

type UnlockedAccount = {
  id: string;
  name: string;
}

通過as重新映射類型

在TypeScript 4.1及更高版本中,可以在映射類型中使用as子句重新映射映射類型中的鍵,形式如下:

type MappedTypeWithNewProperties<Type> = {
    [Properties in keyof Type as NewKeyType]: Type[Properties]
}

示例一,根據已知類型的鍵映射出新類型鍵

Capitalize[4]: 轉換字符串類型第一個字母為大寫

type Getters<Type> = {
    [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};
 
interface Person {
    name: string;
    age: number;
    location: string;
}
 
type LazyPerson = Getters<Person>;

// 最終LazyPerson 等效于

type LazyPerson = {
    getName: () => string;
    getAge: () => number;
    getLocation: () => string;
}

示例二:映射任意聯合類型

如:映射聯合對象類型,并以類型的Value為新類型的key

type EventConfig<Events extends { kind: string }> = {
    [E in Events as E["kind"]]: (event: E) => void;
}
 
type SquareEvent = { kind: "square", x: number, y: number };
type CircleEvent = { kind: "circle", radius: number };
 
type Config = EventConfig<SquareEvent | CircleEvent>

// 最終config等效于

type Config = {
    square: (event: SquareEvent) => void;
    circle: (event: CircleEvent) => void;
}

該文章在 2025/1/24 16:54:47 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 国产午夜亚洲精品 | 曰韩免费无码av一区二区 | 亚洲精品国产91久久久久久 | 午夜久久久精品一区二区三区 | 国产成人高潮拍拍拍18毛片 | 久操国产在线 | 国产精品久久欧美一区 | 国产swag在线观看 | 久久久久毛片免费观看 | 亚洲欧洲另类色图 | 厨房少妇人妻好深太紧了 | 麻豆一姐视传媒短视频在线观看 | 无套内谢的新婚少妇国语播放 | 久久国产伦子伦精品 | 久久996国产精品免费 | 丁香婷婷久久大综合 | 国产又爽又大又黄A片 | 国产一卡2卡3卡4卡无卡免费视频 | 亚洲无码123 | 无套内谢少妇毛片A片免费视频 | 色妺妺在线视频喷水 | 日本牲交大片免费观看 | 国产亚洲精久久久久久无码苍井空 | 丁香花在线观看免费观看 | 成人羞羞网站入口免费 羞羞视频网站 | 日本国产高清网色视频网站 | 日韩黄色免费观看 | 视频一区久久手机在线 | 日本理论电线在2020鲁大师 | 久久久99精品免费观看精品 | 欧美三级不卡在线观看视频 | 精产国品一二三产品天堂 | 77777亚洲午夜久久多喷 | 国产v亚洲v天堂无码久久久 | 亚洲综合久久1区2区3区 | AV高清一区二区三区色欲 | 2024年国产高中毛片在线视频 | 欧美老熟妇乱子伦牲交视频 | 日韩福利影视 午夜亚欧一区 | 国产精品爽黄69天堂a免费观影完整 | 国产无人区码卡二卡3卡4卡高清在线观看 |