今日已更新 287 条资讯 | 累计 20259 条内容
关于我们

标签:#javascript

找到 546 篇相关文章

AI 资讯

I Built Minesweeper in ~50 Lines — the Only Hard Part Is Flood-Fill

Minesweeper feels intricate — numbers, cascading reveals, flags. Build it and you find it's a grid, a neighbour count, and one recursive function . This is Day 6 of my GameFromZero series. Each cell holds four facts const cell = { mine : false , open : false , flag : false , n : 0 }; n = how many of the 8 neighbours are mines. That number is all the player gets to reason about. Count neighbours once After scattering mines randomly, precompute every non-mine cell's n : let n = 0 ; neighbours ( r , c , ( rr , cc ) => { if ( cells [ rr ][ cc ]. mine ) n ++ ; }); cell . n = n ; Flood-fill is the whole trick When you open a cell with zero neighbouring mines, there's nothing dangerous nearby — so auto-open all 8 neighbours, and if any of those are also zero, they cascade. That's why one click can clear half the board. It's recursion: function open ( r , c ) { const cell = cells [ r ][ c ]; if ( cell . open || cell . flag ) return ; // base case cell . open = true ; if ( cell . n === 0 ) neighbours ( r , c , ( rr , cc ) => open ( rr , cc )); // recurse } This is the same algorithm behind the paint-bucket tool and maze region-filling. Flags + win/lose Right-click toggles a flag (and blocks accidental opens). Click a mine → lose. Win when opened cells = total − mines: if ( cell . mine ) gameOver (); if ( opened === R * C - M ) win (); That's the entire game. Master the state-step-draw loop once and every classic — Snake, Pong, Tetris, 2048, Minesweeper — is an evening each. ▶️ Play it + read the step-by-step breakdown: https://dev48v.infy.uk/game/day6-minesweeper.html Day 6 of GameFromZero.

2026-06-14 原文 →
开发者

I Built a 4-Sided Plot Area Calculator with 2D & 3D Visualization

I Built a 4-Sided Plot Area Calculator with 2D & 3D Visualization Most online plot calculators only work for simple rectangular plots. However, many real-world properties have four sides with different measurements, making area estimation much more difficult. That's why I built a 4-Sided Plot Area Calculator that allows users to enter the North, South, East, and West dimensions and instantly calculate the approximate plot area. 🔗 https://www.premiumconverters.com/plot-area-calculator Features 📐 Supports irregular 4-sided plots 🏠 Calculates area in Marla, Kanal, Acres, and more 🖼️ Interactive 2D top-down visualization 🏗️ Isometric 3D plot rendering 📏 Feet & inches input support 📱 Mobile-friendly experience Why I Built It In many countries, especially in South Asia, property dimensions are often recorded as side measurements rather than perfect geometric shapes. Existing tools rarely address this use case properly. I wanted to create a simple solution that homeowners, buyers, real estate professionals, and developers could use without needing complex surveying software. The Result The calculator transforms four side lengths into a practical estimate while providing visual feedback that helps users better understand their property's shape. Building tools that solve real-world problems is one of the most rewarding parts of software engineering. Have you ever built a niche tool that unexpectedly helped thousands of users?

2026-06-14 原文 →
开发者

Day 26 of Learning MERN Stack

Hello Dev Community! 👋 It is officially Day 26 of my journey to master the MERN stack! Today, I continued with Lecture 9 of Apna College's JavaScript playlist with Shradha Didi, transitioning from raw prototype object manipulation into modern ES6 structural design: Classes and Inheritance . Yesterday we saw how single objects share methods; today I learned how to create scalable blueprints to manufacture objects efficiently. 🧠 Key Learnings From JS Lecture 9 (Classes & OOP) I explored the professional layout of Object-Oriented Programming (OOP) in modern JavaScript: 1. What is a Class and a Constructor? A class is a standardized blueprint for creating objects. Inside every class, we can define a special method called a constructor() . The constructor triggers automatically the exact moment a new object is instantiated using the new keyword. It is the standard place to initialize instance properties dynamically. javascript class Car { constructor(brand, hp) { this.brandName = brand; this.horsepower = hp; } } let myCar = new Car("Toyota", 180); // Instantiates a fresh object instantly

2026-06-14 原文 →
AI 资讯

Edge Computing in the Browser: How I Replaced a Backend Server with Web Workers & WASM

The obsession with centralizing heavy compute on backend servers is a massive bottleneck for both cost and latency. In 2026, as more applications move to the edge, developers are realizing that the user's browser is an incredibly powerful, untapped compute engine. Recently, I challenged myself to build a free live chess game analyzer for my developer utility suite, CipherKit. The traditional architecture for this requires passing FEN strings to a dedicated backend cluster running the Stockfish engine, which introduces network latency and scales operational costs linearly. I wanted to achieve a 100% client-side, zero-latency experience. Here is how I offloaded the heavy lifting entirely to the browser edge. The Architecture: WASM + Web Workers Running a heavy calculation engine directly in JavaScript instantly blocks the main UI thread. To achieve a flawless 60fps UI, I completely decoupled the state from the computation. The UI Thread: Handles strict DOM rendering, board states, and piece animations. The Worker Thread: Instantiates the Stockfish engine via WebAssembly within the browser's memory. When a live game update occurs, the main thread fires a simple FEN payload via worker.postMessage() . The Worker processes the deep-line evaluations (Depth 20+) asynchronously in the background. It then streams the evaluation lines back to the main thread without causing a single micro-freeze. The Result By treating the browser as the edge compute layer, the tool achieves: Zero Server Latency: Bypassing API rate limits and network bottlenecks. $0 Infrastructure Cost: Heavy compute is crowd-sourced to the user's local device. Absolute Privacy: Sensitive payloads never leave the browser. If you want to see this local asynchronous thread management in action, you can test the live analyzer (and inspect the network tab) here: 👉 CipherKit Live Chess Analyzer Are you offloading heavy computations to the client side in your current projects, or are you still relying on traditional

2026-06-14 原文 →
AI 资讯

Generating valid .ics calendar feeds at build time

A few weeks ago I shipped a feature I'd been putting off because it felt like it needed a backend: subscribable calendar feeds. "Add this holiday to Google Calendar." "Subscribe to all your country's public holidays so they show up in Apple Calendar forever." Every calendar competitor has this. My site had none. The catch: the whole thing is a static export — next build produces a folder of HTML/CSS/JS that I drop on Cloudflare Pages. No server, no API routes at request time, no ISR. So how do you serve a .ics feed that a calendar app polls every few hours? Turns out you don't need a server at all. Here's the approach, the RFC 5545 gotchas that bit me, and the parts I'd tell my past self. The "aha": a feed is just a file A .ics subscription feed is not a live API. It's a static text file that calendar clients re-fetch on a schedule. So for a static site, the idiomatic move is a post-build emitter : after next build , run a Node script that walks your data and writes assets straight into out/ . # scripts/deploy.sh npx next build node scripts/emit-feeds.mjs # writes .ics + .json into out/ That's the entire architecture. The emitter reads the same JSON the pages render from, so the feeds can never drift out of sync with the site — there's one source of truth. It emits: a per-year feed ( holidays-de-2026.ics ) a per-holiday feed (one event, for the "download this day" button) an all-years subscription feed (the one you point webcal:// at) and, almost for free in the same loop, a JSON API under out/api/ No new pages, no new routes. Just files. RFC 5545: all-day events are sneakier than they look I assumed an all-day event on Jan 1 would be DTSTART:20260101 , DTEND:20260101 . Wrong. DTEND is exclusive. A one-day all-day event ends on Jan 2 : BEGIN:VEVENT UID:de-2026-neujahr@calendana.com DTSTAMP:20260614T101500Z DTSTART;VALUE=DATE:20260101 DTEND;VALUE=DATE:20260102 SUMMARY:Neujahr TRANSP:TRANSPARENT CATEGORIES:Holiday END:VEVENT Get this wrong and some clients render a ze

2026-06-14 原文 →
AI 资讯

JSONata Explained: Query and Transform JSON Without the Boilerplate

Working with complex JSON payloads can quickly become a nightmare. You end up chaining .map() , .filter() , and .reduce() calls across multiple lines just to pull out a few nested values. Add optional chaining to avoid crashes and the code becomes nearly unreadable. There is a cleaner way - JSONata . It is a compact, purpose-built query and transformation language for JSON data. Think of it as XPath for XML, but designed from the ground up to work with JSON objects and arrays. What is JSONata? JSONata is an open-source project originally created by Andrew Coleman at IBM. It gives developers a declarative syntax to extract and reshape JSON data without writing procedural JavaScript loops. Where vanilla JS might take 15 lines, a JSONata expression often takes one. It is available as an npm package and integrates naturally into Node.js and TypeScript projects. Simple Path Navigation The foundation of JSONata is its dot-notation path traversal. Given a nested JSON object, you simply trace the path to the value you need: customer.address.city This returns the city value without any need for null checks or defensive coding. JSONata handles missing properties gracefully by returning undefined rather than throwing errors. Automatic Array Mapping When JSONata encounters an array during path traversal, it automatically maps across all items. There is no need to write an explicit .map() call: customer.orders.product This returns an array of all product names from every order in one clean expression. Inline Filtering You can filter arrays directly using bracket notation with a condition: customer.orders[price > 1000].product This returns only the products from orders where the price exceeds 1000. No .filter() callback required. Built-in Aggregation Functions JSONata ships with a solid set of built-in functions for math, strings, and arrays. Aggregating a set of values is straightforward: $sum(customer.orders.price) Other useful functions include $count() , $average() , $string(

2026-06-14 原文 →
开发者

I Spent 30 Days Building a Complete Node.js Learning Path (Free for Everyone)

What This Repository Is A complete, structured, beginner-friendly Node.js learning path. 30 sessions. Each session has Clear learning objectives Step-by-step explanations Working code examples Practice exercises Interview questions Summary of key points No fluff. No assumptions. Just code. The Complete Curriculum Phase 1 - Node.js Fundamentals (Sessions 1-5) Session Topic What You Will Build 01 Introduction to Node.js Your first Node.js program 02 Project Setup and npm package.json, node_modules 03 How Node.js Works Event loop, blocking vs non-blocking 04 Modules and Imports Your first custom module 05 File System Module Read, write, update, delete files Sample code from Session 05 const fs = require ( " fs " ); // Create a file fs . writeFileSync ( " student.txt " , " Welcome To Node.js " ); // Read the file const data = fs . readFileSync ( " student.txt " , " utf8 " ); console . log ( data ); // Welcome To Node.js // Append to file fs . appendFileSync ( " student.txt " , " \n New line added " ); // Delete file fs . unlinkSync ( " student.txt " ); Phase 2 - Core Modules (Sessions 6-10) Session Topic What You Will Build 06 Path Module Cross-platform file paths 07 OS Module System information 08 Events and EventEmitter Custom event handling 09 HTTP Module Create a server 10 Multi-Route Server Multiple routes, JSON responses Sample code from Session 10 const http = require ( " http " ); const server = http . createServer (( req , res ) => { if ( req . url === " / " ) { res . end ( " Home Page " ); } else if ( req . url === " /about " ) { res . end ( " About Page " ); } else if ( req . url === " /products " ) { res . setHeader ( " Content-Type " , " application/json " ); res . end ( JSON . stringify ([{ id : 1 , name : " Laptop " }])); } else { res . statusCode = 404 ; res . end ( " Page Not Found " ); } }); server . listen ( 3000 ); Phase 3 - Building REST APIs (Sessions 11-15) Session Topic What You Will Build 11 CRUD with Dummy Data Complete REST API using array 12

2026-06-13 原文 →
AI 资讯

Reading a Paginated API Without Holding the Whole Thing in Memory

Your API hands out 50 records at a time across 400 pages. You need all of them. You do not need them all at once. Here's a very familiar situation that shows up constantly on the backend. Some API returns data in pages, 50 or 100 records at a time, and you need to walk every page: sync them to your database, export them to a file, run a report. The endpoint gives you a cursor or a page number and you keep asking until there's nothing left. The way most of us write it the first time looks like this: async function getAllRecords () { const all = []; let cursor = 0 ; while ( cursor !== null ) { const { records , nextCursor } = await fetchPage ( cursor ); all . push (... records ); cursor = nextCursor ; } return all ; } const everything = await getAllRecords (); for ( const record of everything ) { process ( record ); } It works. At four hundred records it's fine. The trouble starts when the dataset grows, and it has three separate problems hiding in it. It holds the entire dataset in memory before you touch a single record. It's all or nothing: if page 380 fails, you've thrown away the 19,000 records you already fetched . And it's eager. You can't start processing record one until the very last page has landed , even if all you wanted was the first ten. There's a shape in JavaScript built for exactly this, and if you read the first two posts in this series you already have both halves of it. Two ideas you've already seen In the CSV post , we pulled rows out of a huge file one at a time with a generator, so the file never fully loaded into memory. Lazy. Pull-based. You ask for the next row, you get the next row, nothing more. In the async/await post , we saw that a generator can pause at a yield and resume later.A generator can hold its place across an asynchronous gap. Put those together. A generator that pulls data lazily, and can pause to await something between pulls. That's an async generator, and it's the natural tool for walking a paginated API. You pull records

2026-06-13 原文 →
开发者

An Itty Bitty Aster Plotter problem...

Eight years ago (a geological epoch or two ago in Internet terms) Nicholas Jitkoff released itty.bitty.site - a website which could render whole websites just based on what was in the link, something like: itty.bitty.site?SOMEBASE64ENCODEDVALUE== et voilà! Free web-hosting if you could make it fit ;) At the time, I was rather obsessed with qr-codes thanks to developing QRGoPass and was working with aster plots a lot, so I developed an app that could fit into a qr-code! Today itty.bitty.site no longer exists so I can't do that any more... But I did make it 80% smaller without "cheating" and using modern CSS instead of d3.js ;)

2026-06-13 原文 →
AI 资讯

I built a document converter that never uploads your files

Every time you use an online PDF converter, your file travels to a server somewhere — processed by a company you don't know, stored temporarily on hardware you don't control. For a random meme? Fine. For a payslip, a contract, or a medical document? That's a real privacy problem. What I built ConvertiZen is a document converter that runs 100% in the browser using WebAssembly and modern JS APIs. Your file never leaves your device. Ever. Verify it yourself: open DevTools > Network tab > run a conversion. Zero outgoing requests containing your file data. What it supports 40+ format pairs: PDF ↔ Word, JPG, PNG, Text, HTML, Markdown Excel ↔ CSV, JSON, HTML Images: JPG ↔ PNG ↔ WebP, GIF/BMP → PDF JSON ↔ CSV, Markdown ↔ HTML, XML → JSON How it works PDF.js for PDF parsing docx library for Word generation SheetJS for Excel/CSV Canvas API for image conversions Everything client-side — no server required Pricing 3 free conversions/day, no account needed. Beyond that: €0.69/conversion, €4.99 for a pack of 10, or €4.99/month for unlimited Premium. Feedback welcome What formats are missing? What would make you trust a browser-based tool over a server-based one? 👉 https://convertizen.netlify.app

2026-06-13 原文 →
AI 资讯

How to Convert Word to PDF in the Browser with Vue 3, mammoth, and html2pdf.js

Converting Word documents to PDFs on the server is the classic approach: upload the file, run LibreOffice or a cloud API, send the result back. But that means your users’ resumes, contracts, and reports touch your infrastructure. I wanted something simpler for en.sotool.top : pick a .docx file in the browser, preview the parsed content, and download a PDF. No server involved. Here is how I built it with Vue 3, mammoth , and html2pdf.js . Why Client-Side? The main reason is privacy. Resumes, contracts, tax documents — users do not want them on a stranger’s server. Client-side conversion also means: No upload bandwidth limits No file size caps from your server No storage to clean up Works offline after the page loads The trade-off is that very complex documents are limited by the browser’s rendering capabilities. For typical office documents, that is fine. The Stack Vue 3 — UI, file handling, and reactive state mammoth — Parse .docx files into clean HTML html2pdf.js — Render the HTML into a PDF using html2canvas + jsPDF Native File API — File selection npm install mammoth html2pdf.js Loading the Word Document The first step is reading the uploaded .docx file into an ArrayBuffer , then converting it to HTML with mammoth . import mammoth from ' mammoth ' ; async function convertDocxToHtml ( file ) { const arrayBuffer = await file . arrayBuffer (); const result = await mammoth . convertToHtml ({ arrayBuffer }); return result . value ; } mammoth intentionally produces simple, clean HTML. It ignores complex formatting like text boxes and embedded fonts, which makes the output predictable. I keep the HTML in a reactive ref and render it in a preview panel: < template > <div ref= "previewRef" class= "word-preview" v-html= "htmlContent" ></div> </ template > < script setup > import { ref } from ' vue ' ; const htmlContent = ref ( '' ); const previewRef = ref ( null ); </ script > Generating the PDF Once the user is happy with the preview, html2pdf.js turns the preview element

2026-06-13 原文 →
AI 资讯

What Nobody Told Me About Maintaining an Open Source Project

I am a solo learner. I started coding last year with the help of AI and sometimes without any tutorials or courses. At first, I thought this journey would be easier. But soon I realized something important — no AI or tool can fully solve the real problems I was facing as a developer. I used AI a lot. It explained things with confidence and even provided code. But when I ran that code in my terminal, many times it didn’t work. That’s when I understood something important: AI can guide, but it cannot replace understanding. After facing these issues, I changed my way of learning. Instead of blindly trusting AI, I started: Finding real open-source projects Studying how they were built Listing important topics from those projects Reading documentation carefully Asking AI to explain specific lines of code This helped me understand real-world code better. From this learning journey, I realized something: I should also build my own open-source projects. At first, I believed that creating a powerful project could automatically bring attention and users. But I was wrong. I made a mistake — I was not active on any platform. I was just coding inside VS Code, without communication or sharing my work anywhere. Then I realized: Being a developer is not only about coding. Visibility and communication are also important. After that realization, I started being active on platforms like Dev.to, LinkedIn, and other developer communities. I started posting my work and sharing my progress. Even though I didn’t get many comments, I started getting reactions and engagement. That small feedback gave me motivation. From this journey, I learned something important: Open source is not only about code. It is about helping other developers, sharing knowledge, and being consistent and visible. A developer should not only code silently but also participate in the community. Now I understand that coding is only one part of being a developer. Community, communication, and consistency are equally imp

2026-06-13 原文 →
AI 资讯

Why Retry Is One Of The Most Dangerous Keywords In Software

Few lines of code look more innocent than this: retry ( 3 ) It feels responsible. Professional. Resilient. After all, networks fail. Servers become unavailable. Databases occasionally time out. Retrying seems like the obvious solution. And sometimes it is. But after enough years building production systems, I've become convinced of something: Retry is one of the most dangerous keywords in software. Not because retries are bad. Because retries amplify everything. Good systems become more reliable. Bad systems become disasters. The problem is that many developers treat retries as a reliability feature when they're actually a distributed systems feature. And distributed systems are where simple ideas go to become complicated. Why Retries Exist Imagine: await fetch ( " /api/users " ); The request fails. Maybe: Network hiccup Temporary database issue Load balancer restart Service deployment The operation might succeed if attempted again. So we write: retry ( 3 ) Seems reasonable. And in many cases: It Works Which is why retries become popular. The Dangerous Assumption Most developers unconsciously assume: Failure = Operation Did Not Execute Unfortunately that's not always true. A request can: Execute Successfully ↓ Response Never Arrives From the client's perspective: Failure From the server's perspective: Success Now a retry becomes dangerous. The Double Payment Problem Imagine a payment service. await chargeCard ( order ); The card processor successfully charges: $100 The response is lost due to a network issue. Client sees: Request Failed and retries. await chargeCard ( order ); again. Now: Charge #1 = Success Charge #2 = Success The customer paid twice. Nobody wrote bad logic. The retry created the bug. The Email Storm Problem Consider: await sendWelcomeEmail ( user ); Email provider accepts the message. Response times out. Application retries. await sendWelcomeEmail ( user ); again. Customer receives: Welcome! Welcome! Welcome! Welcome! Support ticket created. Marke

2026-06-13 原文 →
AI 资讯

No Suggest - distraction-free YouTube client

I have been frustrated with YouTube for a while. Not the content, but the everything around it. The homepage full of bait, the auto-play into things I didn't ask for, the Shorts that hijack your scroll, the recommendations that somehow know exactly what will keep you there longest. So I built NoSuggest. What it is A YouTube feed reader that shows you only the channels you follow, nothing else. No algorithm, no recommendations, no Shorts, no homepage, no auto-play, no endless side cards of videos. You add a channel, it fetches their latest videos, done. It lives at nosuggest.com and installs as a PWA on any device — iPhone, Android, desktop — straight from the browser. No app store. The interesting technical constraint: one HTML file The entire app is a single index.html. No account setup, no sign-in, no data collection. Everything that needs to persist — your channel list, saved videos, settings — lives in localStorage. No search history. No watch history. No "you might also like." No trending section. No notification badges designed to create anxiety. No dark patterns anywhere. Every time I was tempted to add something convenient, I asked: does this serve the user's intention, or does it serve engagement? If it was the latter, it didn't make the cut. Try it nosuggest.com — Source Available here , free forever. Curious what others think about this as useful. Thank you.

2026-06-13 原文 →