惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Listify a JavaScript Array
2021-02-18 · via Kent C. Dodds Blog

When you want to display a list of items to a user, I'm afraid .join(', ') just won't cut it:

console.log(['apple'].join(', ')) // apple
// looks good
console.log(['apple', 'grape'].join(', ')) // apple, grape
// nah, I want "apple and grape"
console.log(['apple', 'grape', 'pear'].join(', ')) // apple, grape, pear
// wut?

Ok, so bust out your string concat skills right? That's what I did... but holdup, there's a better way:

Have you heard of Intl.ListFormat? Well, it's likely that this can do all you need and more. Let's take a look:

const items = [
	'Sojourner',
	'Opportunity',
	'Spirit',
	'Curiosity',
	'Perseverance',
]

const formatter = new Intl.ListFormat('en', {
	style: 'long',
	type: 'conjunction',
})
console.log(formatter.format(items))
// logs: "Sojourner, Opportunity, Spirit, Curiosity, and Perseverance"

The cool thing about this is that because it's coming from the Intl standard, a TON of locales are supported, so you can get internationalization for "free".

The first argument to the ListFormat constructor is the locale (we're using 'en' above for "English"). The second argument is the options of style and type. The style option can be one of 'long', 'short', or 'narrow'. The type can be one of 'conjunction', 'disjunction', or 'unit'.

With the list above, here's all the combination of those (with en as the locale):

long
conjunctionSojourner, Opportunity, Spirit, Curiosity, and Perseverance
disjunctionSojourner, Opportunity, Spirit, Curiosity, or Perseverance
unitSojourner, Opportunity, Spirit, Curiosity, Perseverance
short
conjunctionSojourner, Opportunity, Spirit, Curiosity, & Perseverance
disjunctionSojourner, Opportunity, Spirit, Curiosity, or Perseverance
unitSojourner, Opportunity, Spirit, Curiosity, Perseverance
narrow
conjunctionSojourner, Opportunity, Spirit, Curiosity, Perseverance
disjunctionSojourner, Opportunity, Spirit, Curiosity, or Perseverance
unitSojourner Opportunity Spirit Curiosity Perseverance

Interestingly, if we play around with the locale, things behave unexpectedly:

new Intl.ListFormat('en', { style: 'narrow', type: 'unit' }).format(items)
// Sojourner Opportunity Spirit Curiosity Perseverance

new Intl.ListFormat('es', { style: 'narrow', type: 'unit' }).format(items)
// Sojourner Opportunity Spirit Curiosity Perseverance

new Intl.ListFormat('de', { style: 'narrow', type: 'unit' }).format(items)
// Sojourner, Opportunity, Spirit, Curiosity und Perseverance

Perhaps German speakers can clear up for us why the combo of narrow and unit for de behaves more like long and conjunction because I have no idea.

There's also a lesser-known localeMatcher option which can be configured to either 'lookup' or 'best fit' (defaults to 'best fit'). As far as I can tell from mdn, its purpose is to tell the browser how to determine which locale to use based on the one given in the constructor. In my own testing I was unable to determine a difference in functionality switching between these options 🤷‍♂️

Frankly, I think it's typically better to trust the browser on stuff like this rather than write what the browser offers. This is because the longer I spend time writing software, the more I find that things are rarely as simple as we think they'll be (especially when it comes to internationalization). But there are definitely times where the platform comes up short and you can't quite do what you're looking to do. That's when it makes sense to do it yourself.

So I put together a little function that suited my use case pretty well, and I want to share it with you. Before I do, I want to be clear that I did try this without reduce (using a for loop) and I think the reduce method was considerably simpler. Feel free to take a whack at the for loop version though if you want.

function listify(
	array,
	{ conjunction = 'and ', stringify = (item) => item.toString() } = {},
) {
	return array.reduce((list, item, index) => {
		if (index === 0) return stringify(item)
		if (index === array.length - 1) {
			if (index === 1) return `${list} ${conjunction}${stringify(item)}`
			else return `${list}, ${conjunction}${stringify(item)}`
		}
		return `${list}, ${stringify(item)}`
	}, '')
}

In my codebase, is used like so:

const to = `To: ${listify(mentionedMembersNicknames)}`
// and
const didYouMean = `Did you mean ${listify(closeMatches, {
	conjunction: 'or ',
})}?`

I'd take the time to walk through this code with you, but actually as I was writing this post, I realized that my use case wasn't as special as I thought it was and I tried rewriting this to use Intl.ListFormat and wouldn't you know it, with a small change to the API, I was able to make a simpler implementation on top of the standard:

function listify(
	array,
	{
		type = 'conjunction',
		style = 'long',
		stringify = (item) => item.toString(),
	} = {},
) {
	const stringified = array.map((item) => stringify(item))
	const formatter = new Intl.ListFormat('en', { style, type })
	return formatter.format(stringified)
}

With that, now I do this:

// no change for the default case
const to = `To: ${listify(mentionedMembersNicknames)}`
// switch to using the "type" option rather than overloading/abusing the term "conjunction"
const didYouMean = `Did you mean ${listify(closeMatches, {
	type: 'disjunction',
})}?`

Conclusion

So it just goes to show you that you might be doing some extra work that you might not need to be doing. The platform probably does this for you automatically! Oh, and just for fun, here's a TypeScript version of that finished code (I'm in the process of migrating this project to TypeScript).

// unfortunately TypeScript doesn't have Intl.ListFormat yet 😢
// so we'll just add it ourselves:
type ListFormatOptions = {
	type?: 'conjunction' | 'disjunction' | 'unit'
	style?: 'long' | 'short' | 'narrow'
	localeMatcher?: 'lookup' | 'best fit'
}
declare namespace Intl {
	class ListFormat {
		constructor(locale: string, options: ListFormatOptions)
		public format: (items: Array<string>) => string
	}
}

type ListifyOptions<ItemType> = {
	type?: ListFormatOptions['type']
	style?: ListFormatOptions['style']
	stringify?: (item: ItemType) => string
}
function listify<ItemType>(
	array: Array<ItemType>,
	{
		type = 'conjunction',
		style = 'long',
		stringify = (thing: { toString(): string }) => thing.toString(),
	}: ListifyOptions<ItemType> = {},
) {
	const stringified = array.map((item) => stringify(item))
	const formatter = new Intl.ListFormat('en', { style, type })
	return formatter.format(stringified)
}

And now we get sweet autocomplete for those options and type checking on that stringify method. Nice!

Oh, by the way, you'll always want to double-check browser support for whatever you're using. There's caniuse.com and the MDN article on Intl.ListFormat also has a chart.

I hope that was interesting and useful to you!