首页 > 其他分享 >ES 2024 新特性

ES 2024 新特性

时间:2024-05-13 14:21:20浏览次数:24  
标签:const name 特性 2024 Promise type groupBy ES quantity

ECMAScript 2024 新特性

ECMAScript 2024, the 15th edition, added facilities for resizing and transferring ArrayBuffers and SharedArrayBuffers; added a new RegExp /v flag for creating RegExps with more advanced features for working with sets of strings; and introduced the Promise.withResolvers convenience method for constructing Promises, the Object.groupBy and Map.groupBy methods for aggregating data, the Atomics.waitAsync method for asynchronously waiting for a change to shared memory, and the String.prototype.isWellFormed and String.prototype.toWellFormed methods for checking and ensuring that strings contain only well-formed Unicode.

ECMAScript 2024,第 15 版,添加了用于调整 ArrayBufferSharedArrayBuffer 大小和传输的功能; 添加了一个新的 RegExp /v 标志,用于创建具有更高级功能的 RegExp,用于处理字符串集; 并介绍了用于构造 PromisePromise.withResolvers 便捷方法、用于聚合数据的 Object.groupByMap.groupBy 方法、用于异步等待共享内存更改的 Atomics.waitAsync 方法以及 String.prototype.isWellFormedString.prototype.toWellFormed 方法,用于检查并确保字符串仅包含格式正确的 Unicode

一、Promise.withResolvers ( )

This function returns an object with three properties: a new promise together with the resolve and reject functions associated with it.

该函数返回一个具有三个属性的对象:一个新的 Promise 以及与其关联的解决和拒绝函数。

1. 返回值

包含以下属性的普通对象:

1.1. promise

一个 Promise 对象。

1.2. resolve

一个函数,用于解决该 Promise

1.3. reject

一个函数,用于拒绝该 Promise

2. 示例

Promise.withResolvers() 的使用场景是,当你有一个 promise,需要通过无法包装在 promise 执行器内的某个事件监听器来解决或拒绝。

async function* readableToAsyncIterable(stream) {
  let { promise, resolve, reject } = Promise.withResolvers();
  stream.on("error", (error) => reject(error));
  stream.on("end", () => resolve());
  stream.on("readable", () => resolve());

  while (stream.readable) {
    await promise;
    let chunk;
    while ((chunk = stream.read())) {
      yield chunk;
    }
    ({ promise, resolve, reject } = Promise.withResolvers());
  }
}

3. 等价于

Promise.withResolvers() 完全等同于以下代码:

let resolve, reject;
const promise = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

使用 Promise.withResolvers() 关键的区别在于解决和拒绝函数现在与 Promise 本身处于同一作用域,而不是在执行器中被创建和一次性使用。

4. 在非 Promise 构造函数上调用 withResolvers()

Promise.withResolvers() 是一个通用方法。它可以在任何实现了与 Promise() 构造函数相同签名的构造函数上调用。

例如,我们可以在一个将 console.log 作为 resolvereject 函数传入给 executor 的构造函数上调用它:

class NotPromise {
  constructor(executor) {
    // “resolve”和“reject”函数和原生的 promise 的行为完全不同
    // 但 Promise.withResolvers() 只是返回它们,就像是原生的 promise 一样
    executor(
      (value) => console.log("以", value, "解决"),
      (reason) => console.log("以", reason, "拒绝"),
    );
  }
}
const { promise, resolve, reject } = Promise.withResolvers.call(NotPromise);
resolve("hello");

二、Object.groupBy ( items, callbackfn )

callbackfn is called with two arguments: the value of the element and the index of the element.

The return value of groupBy is an object that does not inherit from %Object.prototype%.

callbackfn 是一个接受两个参数的函数。 groupByitems 中的每个元素按升序调用一次 callbackfn,并构造一个新对象。 Callbackfn 返回的每个值都被强制转换为属性键。 对于每个这样的属性键,结果对象都有一个属性,其键是该属性键,其值是一个数组,其中包含回调函数返回值强制为该键的所有元素。

使用两个参数调用 callbackfn:元素的值和元素的索引。

groupBy 的返回值是一个不继承自 Object.prototype 的对象。

1. 作用

Object.groupBy() 静态方法根据提供的回调函数返回的字符串值对给定可迭代对象中的元素进行分组。返回的对象具有每个组的单独属性,其中包含组中的元素的数组。

2. 参数

2.1. items

一个将进行元素分组的可迭代对象(例如 Array)。

2.2. callbackFn

对可迭代对象中的每个元素执行的函数。它应该返回一个值,可以被强制转换成属性键(字符串或 symbol),用于指示当前元素所属的分组。该函数被调用时将传入以下参数:

  • element:数组中当前正在处理的元素。
  • index:正在处理的元素在数组中的索引。

3. 返回值

一个带有所有分组属性的 null 原型对象,每个属性都分配了一个包含相关组元素的数组。

4. 示例

4.1. 根据 element 元素分组

Object.groupBy([
  { name: "芦笋", type: "蔬菜", quantity: 5 },
  { name: "香蕉", type: "水果", quantity: 0 },
  { name: "山羊", type: "肉", quantity: 23 },
  { name: "樱桃", type: "水果", quantity: 5 },
  { name: "鱼", type: "肉", quantity: 22 },
], ({name}) => name)
// 输出
/**
{
    "蔬菜": [
        {
            "name": "芦笋",
            "type": "蔬菜",
            "quantity": 5
        }
    ],
    "水果": [
        {
            "name": "香蕉",
            "type": "水果",
            "quantity": 0
        },
        {
            "name": "樱桃",
            "type": "水果",
            "quantity": 5
        }
    ],
    "肉": [
        {
            "name": "山羊",
            "type": "肉",
            "quantity": 23
        },
        {
            "name": "鱼",
            "type": "肉",
            "quantity": 22
        }
    ]
}
*/

4.2. 自定义分组

const myCallback = ({ quantity }) => {
  return quantity > 5 ? "ok" : "restock";
}

const result = Object.groupBy([
  { name: "芦笋", type: "蔬菜", quantity: 5 },
  { name: "香蕉", type: "水果", quantity: 0 },
  { name: "山羊", type: "肉", quantity: 23 },
  { name: "樱桃", type: "水果", quantity: 5 },
  { name: "鱼", type: "肉", quantity: 22 },
], myCallback);
// 输出
/**
{
    "restock": [
        {
            "name": "芦笋",
            "type": "蔬菜",
            "quantity": 5
        },
        {
            "name": "香蕉",
            "type": "水果",
            "quantity": 0
        },
        {
            "name": "樱桃",
            "type": "水果",
            "quantity": 5
        }
    ],
    "ok": [
        {
            "name": "山羊",
            "type": "肉",
            "quantity": 23
        },
        {
            "name": "鱼",
            "type": "肉",
            "quantity": 22
        }
    ]
}
*/

三、Map.groupBy ( items, callbackfn )

callbackfn is called with two arguments: the value of the element and the index of the element.

The return value of groupBy is a Map.

callbackfn 是一个接受两个参数的函数。 groupByitems 中的每个元素按升序调用一次回调函数,并构造一个新的 Mapcallbackfn 返回的每个值都用作 Map 中的键。 对于每个这样的键,结果 Map 都有一个条目,其键是该键,其值是一个数组,其中包含 callbackfn 返回该键的所有元素。

使用两个参数调用 callbackfn:元素的值和元素的索引。

groupBy 的返回值是一个 Map

1. 作用

Map.groupBy() 静态方法使用提供的回调函数返回的值对给定可迭代对象中的元素进行分组。最终返回的 Map 使用测试函数返回的唯一值作为键,可用于获取每个组中的元素组成的数组。

2. 参数

2.1. items

一个将进行元素分组的可迭代对象(例如 Array)。

2.2. callbackFn

对可迭代对象中的每个元素执行的函数。它应该返回一个值(对象或原始类型)来表示当前元素的分组。该函数被调用时将传入以下参数:

  • element:数组中当前正在处理的元素。
  • index:正在处理的元素在数组中的索引。

3. 返回值

一个包含了每一个组的键的 Map 对象,每个键都分配了一个包含关联组元素的数组。

4. 示例

const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy([
  { name: "芦笋", type: "蔬菜", quantity: 9 },
  { name: "香蕉", type: "水果", quantity: 5 },
  { name: "山羊", type: "肉", quantity: 23 },
  { name: "樱桃", type: "水果", quantity: 12 },
  { name: "鱼", type: "肉", quantity: 22 },
], ({ quantity }) =>
  quantity < 6 ? restock : sufficient,
);
// 输出 result Map
/**
new Map([
    [
        {
            "restock": false
        },
        [
            {
                "name": "芦笋",
                "type": "蔬菜",
                "quantity": 9
            },
            {
                "name": "山羊",
                "type": "肉",
                "quantity": 23
            },
            {
                "name": "樱桃",
                "type": "水果",
                "quantity": 12
            },
            {
                "name": "鱼",
                "type": "肉",
                "quantity": 22
            }
        ]
    ],
    [
        {
            "restock": true
        },
        [
            {
                "name": "香蕉",
                "type": "水果",
                "quantity": 5
            }
        ]
    ]
])
*/

image

四、Atomics.waitAsync ( typedArray, index, value, timeout )

This function returns a Promise that is resolved when the calling agent is notified or the the timeout is reached.

此函数返回一个 Promise,当通知调用代理或达到超时时,该 Promise 会被解析。

1. 作用

Atomics.waitAsync() 静态方法异步等待共享内存的特定位置并返回一个 Promise。

2. 参数

  • typedArray:基于 SharedArrayBufferInt32ArrayBigInt64Array
  • indextypedArray 中要等待的位置。
  • value:要测试的期望值。
  • timeout:可选 等待时间,以毫秒为单位。NaN(以及会被转换为 NaN 的值,例如 undefined)会被转换为 Infinity。负值会被转换为 0。

3. 返回值

一个 Object,包含以下属性:

  • async:一个布尔值,指示 value 属性是否为 Promise
  • value:如果 asyncfalse,它将是一个内容为 "not-equal" 或 "timed-out" 的字符串(仅当 timeout 参数为 0 时)。如果 asynctrue,它将会是一个 Promise,其兑现值为一个内容为 "ok" 或 "timed-out" 的字符串。这个 promise 永远不会被拒绝。

4. 异常

  • TypeError:如果 typedArray 不是一个基于 SharedArrayBufferInt32ArrayBigInt64Array,则抛出该异常。
  • RangeError:如果 index 超出 typedArray 的范围,则抛出该异常。

5. 示例

给定一个共享的 Int32Array

const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);

令一个读取线程休眠并在位置 0 处等待,预期该位置的值为 0。result.value 将是一个 promise

const result = Atomics.waitAsync(int32, 0, 0, 1000);
// { async: true, value: Promise {<pending>} }

在该读取线程或另一个线程中,对内存位置 0 调用以令该 promise 为 "ok"。

Atomics.notify(int32, 0);
// { async: true, value: Promise {<fulfilled>: 'ok'} }

如果它没有为 "ok",则共享内存该位置的值不符合预期(value 将是 "not-equal" 而不是一个 promise)或已经超时(该 promise 将为 "time-out")。

五、String.prototype.isWellFormed ( )

1. 作用

isWellFormed() 方法返回一个表示该字符串是否包含单独代理项的布尔值。

1.1. 单独代理项

单独代理项(lone surrogate) 是指满足以下描述之一的 16 位码元:

  • 它在范围 0xD800 到 0xDBFF 内(含)(即为前导代理),但它是字符串中的最后一个码元,或者下一个码元不是后尾代理。
  • 它在范围 0xDC00 到 0xDFFF 内(含)(即为后尾代理),但它是字符串中的第一个码元,或者前一个码元不是前导代理。

2. 返回值

如果字符串不包含单独代理项,返回 true,否则返回 false

3. 示例

const strings = [
  // 单独的前导代理
  "ab\uD800",
  "ab\uD800c",
  // 单独的后尾代理
  "\uDFFFab",
  "c\uDFFFab",
  // 格式正确
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.isWellFormed());
}
// 输出:
// false
// false
// false
// false
// true
// true

六、String.prototype.toWellFormed ( )

1. 作用

toWellFormed() 方法返回一个字符串,其中该字符串的所有单独代理项都被替换为 Unicode 替换字符 U+FFFD

2. 返回值

新的字符串是原字符串的一个拷贝,其中所有的单独代理项被替换为 Unicode 替换字符 U+FFFD

3. 示例

const strings = [
  // 单独的前导代理
  "ab\uD800",
  "ab\uD800c",
  // 单独的后尾代理
  "\uDFFFab",
  "c\uDFFFab",
  // 格式正确
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.toWellFormed());
}
// Logs:
// "ab�"
// "ab�c"
// "�ab"
// "c�ab"
// "abc"
// "ab

标签:const,name,特性,2024,Promise,type,groupBy,ES,quantity
From: https://www.cnblogs.com/risheng/p/18189095

相关文章

  • CentOS7部署ES(单机)
    一、创建路径,解压##创建路径[root@localhost/]#cd/data[root@localhostdata]#mkdirES##解压[root@localhostdata]#cdES[root@localhostES]#lselasticsearch-8.11.3-linux-x86_64.tar.gz[root@localhostES]#tar-zxvfelasticsearch-8.11.3-linux-x86_64.ta......
  • AtCoder Beginner Contest 353
    AtCoderBeginnerContest353abc353_c题意:定义\(F(x,y)\)为\((x+y)mod10^8\)的值,求\(\displaystyle\sum_{i=1}^{N-1}\sum_{j=i+1}^Nf(A_i,A_j).\)思路:对于\(\displaystyle\sum_{i=1}^{N-1}\sum_{j=i+1}^N\f(A_i,A_j).\)来说,每个\(A_i\)的次数都是\(n-1\)次,所以如果没有\(m......
  • HiveSQL
    1.表sublime格式化ctrl+kctrl+f--创建学生表DROPTABLEIFEXISTSstudent_info;createtableifnotexistsstudent_info(stu_idstringCOMMENT'学生id',stu_namestringCOMMENT'学生姓名',birthdaystringCOMMENT'出生日期',......
  • 【pytest】将测试用例内的数据回填给fixtrue 中
    【背景】每个测试用例生成对应的log文件,需要将测试脚本名称传给log对象,生成对于的log文件【分析】方法一:使用@pytest.mark.parametrize的 indirect=True ,参数1:执行对应的函数(fixtrue中的函数名称) 参数2:函数对应的参数  参考:Pytest系列(10)-fixture传参数reques......
  • Dockerfile - build zgrpc-go-professionals:client
     FROM--platform=$BUILDPLATFORMalpineasprotocARGBUILDPLATFORM=linux/amd64TARGETOS=linuxTARGETARCH=amd64#downloadtheprotocbinaryfromgithub#Weunzipthefileinto/usr/local.Noticethatweareextractingboththeprotoc#binary(/bin/pr......
  • 软工计算1—Java篇1 20240513
    Java中的函数重载函数重载(FunctionOverloading)是面向对象编程中的一个概念,它允许在同一个类中定义多个同名函数,但这些函数的参数列表必须不同。参数列表的不同可以体现在参数的类型、数量或顺序上。函数重载使得程序设计更加灵活,可以针对不同的参数类型或数量提供不同的函数实现......
  • Zed——Eslint配置支持Vue
    前言体验下基于Rust的编辑器,看看是不是真的那么快,一个Vue2.0的老项目,其中已经配置好了eslint相应的规则;文档:https://zed.dev/docs/languages/javascript#eslintissue:https://github.com/zed-industries/zed/issues/9934内容配置最开始按着文档来配置,咋搞都没有对Vue.js生......
  • 2024广东大学生攻防大赛WP
    Misc猜一猜题目描述:你们想要的flag就在压缩包里面。压缩包文件名解密解压密码为a1478520然后修改flag.png文件头得到扫描二维码之后❀❁❀❇❀✼❀❂✿❆✿✽❁❀✿✾❂❅✿❄❂❉❀✿❂❆❀❃❀✿❂❆✿❀❁✾✻✿❁❁❀❁❂❊✻❂✿❈=花朵解密https://www.qq......
  • vcenter创建数据中心加入ESXI主机
    vcenter创建数据中心加入ESXI主机 右键选择vcenter主机,点新建数据中心 2、点确定  3、对Datacenter右键,然后选择添加主机 4、添加主机IP地址 5、添加用户密码,然后下一页 6、点是 7、会显示摘要,按下一页 8、分配许可证 9、按是 10、按下一......
  • 在PLC的扫描特性下,FOR循环里面套IF或者定时器会发生什么?
    1.为什么会提出这个题目在PLC指令的执行过程中,FOR循环会在每个扫描周期执行完一个循环,然后程序才会接着往下扫描在PLC指令的执行过程中,IF判断会在每次扫描中判断一次条件,满足则进入执行体,不满足则跳出IF把IF放在FOR循环里面,会导致循环体执行时间过长,或者其他问题吗?(答案是不会......