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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
P
Privacy & Cybersecurity Law Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
S
Security Affairs
Latest news
Latest news
Security Latest
Security Latest
N
News and Events Feed by Topic
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Exploit Database - CXSecurity.com
The Last Watchdog
The Last Watchdog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
博客园_首页
S
Secure Thoughts
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
腾讯CDC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
N
News and Events Feed by Topic
A
Arctic Wolf
MongoDB | Blog
MongoDB | Blog
爱范儿
爱范儿
Project Zero
Project Zero
A
About on SuperTechFans
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Know Your Adversary
Know Your Adversary
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs

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 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 Listify a JavaScript Array 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
Array reduce vs chaining vs for loop
Kent C. Dodds 🏹 @kentcdodds · 2021-05-24 · via Kent C. Dodds Blog

Watch "Array reduce vs chaining vs for loop" on egghead.io

I've been in the process of moving some of my digital life around and one thing that I've had to do is download all of my photos from Google Photos. Thanks to the way those are organized, I found the need to rearrange them, so I wrote a little node script to do it. What the script does is not entirely relevant for this post so I'm not going to go into detail, (but here's the whole thing if you wanna give it a read-through). Here's the bit I want to talk about (edited slightly for clarity):

const lines = execSync(`find "${searchPath}" -type f`).toString().split('\n')

const commands = lines
	.map((f) => f.trim())
	.filter(Boolean)
	.map((file) => {
		const destFile = getDestFile(file)
		const destFileDir = path.dirname(destFile)
		return `mkdir -p "${destFileDir}" && mv "${file}" "${destFile}"`
	})

commands.forEach((command) => execSync(command))

Basically all this does is uses the linux find command to find a list of files in a directory, then separate the results of that script into lines, trim them to get rid of whitespace, remove empty lines, then map those to commands to move those files, and then run those commands.

I shared the script on twitter and had several people critiquing the script and suggest that I could have used reduce instead. I'm pretty sure both of them were suggesting it as a performance optimization because you can reduce (no pun intended) the number of times JavaScript has to loop over the array.

Now, to be clear, there were about 50 thousand items in this array, so definitely more than a few dozen you deal with in typical UI development, but I want to first make a point that in a situation like one-off scripts that you run once and then you're done, performance should basically be the last thing to worry about (unless what you're doing really is super expensive). In my case, it ran plenty fast. The slow part wasn't iterating over the array of elements multiple times, but running the commands.

A few other people suggested that I use Node APIs or even open source modules from npm to help run these scripts because it would "probably be faster and work cross platform." Again, they're probably not wrong, but for one-off scripts that are "fast enough", those things don't matter. This is a classic example of applying irrelevant constraints on a problem resulting in a more complicated solution.

In any case, I did want to address the idea of using reduce instead of the map, filter, then map I have going on there.

With reduce

Here's what that same code would be like if we use reduce

const commands = lines.reduce((accumulator, line) => {
	let file = line.trim()
	if (file) {
		const destFile = getDestFile(file)
		const destFileDir = path.dirname(destFile)
		accumulator.push(`mkdir -p "${destFileDir}" && mv "${file}" "${destFile}"`)
	}
	return accumulator
}, [])

Now, I'm not one of those people who think that reduce is the spawn of the evil one (checkout that thread for interesting examples of reduce), but I do feel like I can recognize when code is actually simpler/more complex and I'd say that the reduce example here is definitely more complex than the chaining example.

With loop

Honestly, I've been using array methods so long, I'll need a second to rewrite this as a for loop. So... one sec...

Ok, here you go:

const commands = []
for (let index = 0; index < lines.length; index++) {
	const line = lines[index]
	const file = line.trim()
	if (file) {
		const destFile = getDestFile(file)
		const destFileDir = path.dirname(destFile)
		commands.push(`mkdir -p "${destFileDir}" && mv "${file}" "${destFile}"`)
	}
}

That's not much simpler either.

EDIT: BUT WAIT! We can simplify this thanks to for..of!

const commands = []
for (const line of lines) {
	const file = line.trim()
	if (!file) continue

	const destFile = getDestFile(file)
	const destFileDir = path.dirname(destFile)
	commands.push(`mkdir -p "${destFileDir}" && mv "${file}" "${destFile}"`)
}

Honestly I do think that's not a whole lot better than the traditional loop, but I do think it's pretty simple. I think some people discount for loops because they're "imperative", when they're actually pretty useful.

My take

Often, I'm going to be choosing between chaining and for..of loops. If I have a performance concern with iterating over the array multiple times, then for..of will definitely be my selection of choice.

I don't often use reduce, but sometimes I'll try it out and compare it to other options and go with that. I realize how subjective that sounds, but so much of coding is subjective so 🤷‍♂️

I'd be interested to hear what you think. Reply to the tweet below and let me know. And feel free to retweet if that's something you're into.