【JavaScript Weekly】2023.11.16

Prettier

Prettier 更新了3.1版本,对三元组的格式化做了更新


Prettier 3.1 Released — The popular opinionated code formatter has a new release including support for the new control flow syntax in Angular 17 plus a new, experimental formatting option for ternary expressions (as in x ? y : z) explained in more depth in “A curious case of the ternaries.”

opinionated: 这个没有直接对应的中文意思,类似于褒义版本的刚愎自用,在 Prettier 的语境下,就是如果不按它那么写就不行,就会报错画红波浪线
control flow 控制流
syntax 语法
experimental 实验性的

A curious case of the ternaries


Formatting nested ternaries 格式化 嵌套的 三元组


Ternary formatting has always been a challenge, and we’re finally addressing it in v3.1.0 with the introduction of a novel formatting style.

addressing 发表
novel 新的


Read on for our journey and the motivation behind this change, along with early developer feedback and an overview of the “curious ternaries” style.

Read on 继续阅读 Please read on for more information.
motivation 动机


introduction


Formatting nested ternaries nicely in a wide variety of scenarios is a surprisingly tricky challenge.

scenarios 场景
tricky challenge 棘手的挑战


Developers have long found them so confusing to read that they end up just refactoring their code to an ugly series of if-else statements, often with a let declaration, an iife, or a separate function entirely.

declaration 声明
iife 立即调用表达式 immediately invoked function expression


According to beta testers, the new formatting style we’ve developed can take some getting used to, but ultimately allows ternaries to be practically used as a concise form of if-else-expressions in modern codebases.

getting used to 开始适应,take some getting used to 是说需要一段时间适应
ultimately 同 finally,还有一个意思是表示强调和重要
concise 简明的


Historical background


Prettier’s original, naïve approach – just add indentation to each level of a nested ternary – worked fine in simple cases, but obviously doesn’t scale to long chains of nested ternaries and had other problems.

naïve 同 naive
indentation 缩进


Challenging criteria

criteria 标准


Ideally, we’d find one scheme that would meet our criteria:

Ideally 理想情况下
scheme 方案


  1. In all cases, it should be easy to follow “what’s the if”, “what’s the then”, and “what’s the else” – and what they map to.

map to 映射到


  1. The code should fluidly flow from a single ternary, to a chain of 2, to a long chain of simple cases, to something more complex with a few nested conditions. (Most alternatives we explored failed this test).

fluidly 流畅地

这个我没大看懂,是优先级的意思嘛


  1. The syntax in JSX, TypeScript conditional expressions (which cannot be expressed with if), and normal JS should all look and feel the same.

比方说 TypeScript 里面有

interface Animal {live(): void;
}
interface Dog extends Animal {woof(): void;
}type Example1 = Dog extends Animal ? number : string;     
// type Example1 = numbertype Example2 = RegExp extends Animal ? number : string;
// type Example2 = string

这里的三元表达式就不能直接用 if 表达式代替

jsx中

render() {const isLoggedIn = this.state.isLoggedIn;return (<div>{isLoggedIn? <LogoutButton onClick={this.handleLogoutClick} />: <LoginButton onClick={this.handleLoginClick} />}</div>);
}

也不能直接用 if 表达式代替


  1. It should scale to nested ternary chains of arbitrary length (imagine a TypeScript conditional type with dozens of alternative cases).

scale to 从一种情况扩展到另一种情况
arbitrary 任意的

这里是指 TS 的情况

type TypeName<T> = T extends string? "string": T extends number? "number": T extends boolean? "boolean": T extends undefined? "undefined": T extends Function? "function": "object";

这样缩进就没有必要了,太冗长


Indented ternaries clearly failed (4), arguably (1), and even (3) – we have almost always printed JSX ternaries in a flat-but-readable format that unfortunately felt unnatural outside of JSX.

我看了他们的链接,JSX 风格就是有好多的括号和换行,看起来就像用小括号括起来的 if else 一样,类似于以下这种:

const StorybookLoader = ({ match }) =>match.params.storyId === "button" ? (<ButtonStorybook />) : match.params.storyId === "color" ? (<ColorBook />) : match.params.storyId === "typography" ? (<TypographyBook />) : match.params.storyId === "loading" ? (<LoaderStorybook />) : match.params.storyId === "deal-list" ? (<DealListStory />) : (<Message><Title>{"Missing story book"}</Title><Content><BackButton /></Content></Message>);

但是呢,非jsx的场景下确实很繁琐

// JSX 型格式
const message =i % 3 === 0 && i % 5 === 0 ? ("fizzbuzz") : i % 3 === 0 ? ("fizz") : i % 5 === 0 ? ("buzz") : (String(i));

Many people in the community were excited about a “case-style”, drawing inspiration from the match syntax from languages like Rust or OCaml, but it did not meet (2) and other goals.

case-style 看起来很优雅,但是体现不出来层次的关系

// case-style 格式
const message =i % 3 === 0 && i % 5 === 0 ? "fizzbuzz" :i % 3 === 0 ? "fizz" :i % 5 === 0 ? "buzz" :String(i);

A surprising solution


The good news is that we found a formatting algorithm that met our criteria. The bad news is that it’s novel, and thus unfamiliar to most developers.

novel 新


In beta testing this feature, we found developers were quite skeptical when they first saw it:

skeptical 怀疑的


But then, after using it for a bit, they didn’t want to go back:

Another developer had this to say:

My first hour with the rule on, it felt a little odd. But by hour two, I’d used it a few times to solve problems that otherwise would have been ugly refactors to if statements. I’m not going back.

I used to hate nested ternaries, but I also hate restructuring a nice line of code into if-else statements. The new rule adds an understandable, linear if-else, if-else expression to the language and is much nicer than multiple ternaries as nested branches.

So we felt we had a winning formula, but we knew it could be a jarring introduction to the community.

winning formula 这是一个俗语,指有效的方式,不一定是字面上的致胜法
jarring 令人震惊


As a result, we decided to put this new formatting behind a temporary --experimental-ternaries option for a few months, and in the meantime go ahead and ship what the community has been clamoring for: indented ternaries.

ship 本意是用船送,这里同 send, transport
clamoring for 吵着要,热切要求的感觉


Styling Overview


So what does this new style look like, anyway?

Here’s a quick, contrived example to show the thinking behind “curious” ternaries:
contrived 直译是人造的,在这应该不是这个含义,更像是它动词转化过来的,表示好
contrive: to think of or make something, for example a plan or a machine, in a clever way

const animalName =pet.canBark() ?pet.isScary() ?'wolf': 'dog': pet.canMeow() ?'cat': 'probably a bunny';
  1. Every line that ends with a question mark is an “if”.
    • If you see foo ? it’s like asking a question about foo – “if foo? then, …”.
  2. Every line that starts with a : is an “else”.
    • If you see : foo that means, “else, foo”.
    • If you see : foo ? that means “else, if foo?”.
  3. Every line without : or ? is a “then”.
    • If you just see foo, that means, “then foo”.

And here’s the code rewritten to demonstrate “case-style” ternaries:
demonstrate 演示

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/155753.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

算法分析与设计课后练习23

求下面的0-1背包问题 &#xff08;1&#xff09;N5,M12,(p1,p2,…,p5)(10,15,6,8,4),(w1,w2,…,w5)(4,6,3,4,2) &#xff08;2&#xff09;N5,M15,(p1,p2,…,p5)(w1,w2,…,w5)(4,4,5,8,9)

深度学习与深度强化学习

1. 深度学习中卷积层的作用是什么&#xff1f;全连接层的作用是什么&#xff1f;二者有什么联系和区别&#xff1f; 在深度学习中&#xff0c;卷积层&#xff08;Convolutional Layer&#xff09;和全连接层&#xff08;Fully Connected Layer&#xff09;是神经网络中常见的两…

Keka v1.3.5(mac压缩解压工具)

Keka是一款功能强大的文件压缩和解压缩软件&#xff0c;为Mac系统用户提供便捷、高效的文件管理工具。以下是Keka的主要特点和功能&#xff1a; 多种压缩格式支持&#xff1a;Keka支持多种常见的压缩格式&#xff0c;包括ZIP、7Z、RAR、TAR、GZIP等。它能够方便地创建和提取这些…

react antd下拉选择框选项内容换行

下拉框选项字太多&#xff0c;默认样式是超出就省略号&#xff0c;需求要换行全展示&#xff0c;选完在选择框里还是要省略的 .less: .aaaDropdown {:global {.ant-select-dropdown-menu-item {white-space: pre-line !important;word-break: break-all !important;}} } html…

mongodb——原理简介,docker单机部署

MongoDB noSQL数据库 特点 数据文件存储格式为 BSON &#xff08;JSON 的扩展&#xff09; &#xff5b;“name”&#xff1a;“joe”&#xff5d;这是 BSON 的例子&#xff0c;其中"name"是键&#xff0c;"joe"是值。键值对组成了 BSON 格式。面向集合…

ROS2中Executors对比和优化

目录 SingleThreadExecutorEventExecutor SingleThreadExecutor 执行流程 EventExecutor 通信图

70. 爬楼梯 --力扣 --JAVA

题目 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f; 解题思路 通过对爬楼梯进行分解&#xff0c;爬到当前台阶的方式分为两种&#xff0c;即由上一个台阶通过爬1和上两个台阶爬2&#xff0c;同公…

Linux学习第43天:Linux 多点电容触摸屏实验:难忘记第一次牵你手的温存

Linux版本号4.1.15 芯片I.MX6ULL 大叔学Linux 品人间百味 思文短情长 人都是性情中人&#xff0c;如果把学习当做自己的女朋友&#xff0c;对她细致入微、掏心掏肺、有耐心有恒心&#xff0c;终会修成正果。 而我们本节需要学习的电…

MySQL -- DQL

1、select查询列和列名&#xff1a; --查询所有员工信息(*通配符&#xff0c;默认查询所有的列) select * from emp;--查询员工的姓名 select ename from emp;--查询员工的薪资 select sal from emp;--查询员工的姓名和薪资 select ename , sal from emp; select ename sal fr…

Vue3封装全局插件

定义一个全局加载组件 一、首先定义dom元素 定义一个index.vue文件 <template><div class"loading">loading...</div> </template> <script setup lang"ts"></script> <style scoped> .loading {display: fl…

(swjtu西南交大)数据库实验(概念数据库设计及逻辑关系转换):音乐软件数据管理系统

一、实体型及属性 &#xff08;20分&#xff09; 用户&#xff08;账号&#xff0c;用户名&#xff0c;密码&#xff0c;性别&#xff0c;生日&#xff0c;地区&#xff0c;手机号&#xff0c;个性签名&#xff0c;信息修改审核客服&#xff09; 歌手&#xff08;歌手号&#…

C++模拟实现——红黑树封装set和map

一、红黑树迭代器的实现 基本的框架和实现链表的迭代器思路是一样的&#xff0c;都是对指针进行封装处理&#xff0c;然后实现一些基本的运算符重载&#xff0c;最重要的是operator&#xff0c;需要不递归的实现走中序的规则&#xff0c;这里只实现那最核心的几个基本功能&…

使用 gpg 对Linux下的文件加密

其实蛮简单的&#xff0c;Linux原生就有gpg命令。 gpg表示GNU Privacy Guard。PGP表示Pretty Good Privacy。有点绕&#xff0c;别搞混。 gpg 是 GNU Privacy Guard (GnuPG) 的 OpenPGP&#xff08;Pretty Good Privacy&#xff09;部分。 它是一个使用 OpenPGP 标准提供数字…

第一次参加算法比赛是什么感受?

大家好&#xff0c;我是怒码少年小码。 冬日暖阳&#xff0c;好日常在。今天中午在食堂干饭的时候&#xff0c;我的手机&#x1f4f1;收到了一条收货信息。 阿&#xff1f;什么玩意儿&#xff1f;我又买啥了&#xff1f; 个败家玩意&#xff0c;我都准备好叨叨我自己&#x…

msvcp120.dll缺失的解决方法与作用介绍

大家好&#xff01;我是小编。今天&#xff0c;我想和大家分享一下关于“找不到msvcp120.dll无法继续执行代码的5个解决方法”的话题。 首先&#xff0c;让我们来了解一下msvcp120.dll的作用。msvcp120.dll是Microsoft Visual C Redistributable Package的一部分&#xff0c;它…

51单片机演奏兰亭序

使用开发板为普中51-实验板 普中-2 时钟频率&#xff1a;11.001081MHZ 演示视频&#xff1a; 【51单片机演奏兰亭序】 https://www.bilibili.com/video/BV12G411D7uK/?share_sourcecopy_web&vd_source0f48f7cc0fef720b95e067122ac83437 源码如下&#xff1a; 数组较大&a…

高防CDN如何预防攻击?

现在网络攻击事件越来越多&#xff0c;而且愈发凶猛&#xff0c;为了保障互联网业务能稳定正常的运行&#xff0c;市场上出现了很多高防产品&#xff0c;例如高防服务器、高防IP、高防CDN等等。其中究竟高防CDN怎么防攻击&#xff0c;能防哪些攻击&#xff1f;高防CDN如何实现防…

git创建新分支将项目挂载到新分支操作

1.如果是本地项目,没有关联过git // 在git创建仓库(默认master分支) // 复制克隆链接(默认下载下来的是master仓库,克隆指定分支如下所示) git clone -b 分支名 克隆地址 // 将某分支克隆下来后,直接将项目放到新文件夹内(执行以下命令提交即可) git add . git commit -m 备注…

maven配置文件

<?xml version"1.0" encoding"UTF-8"?><!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding …

matlab-BP神经网络的训练参数大全

本文部分图文来自《老饼讲解-BP神经网络》bp.bbbdata.com 本文列兴趣MATLAB神经网络工具箱中&#xff0c;训练参数trainParam的各个参数与意义 以方便在使用matlab工具箱时&#xff0c;用于查阅 一、matlab神经网络工具箱trainParam的参数列表 trainParam中的各个具体参数如下…