萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作 LINQ 風格查詢:擴充 Array 原型鏈

C# LINQ 提供強大的集合查詢語法。ES5+ 陣列已內建 forEach, map, filter, reduce, some, every, find, findIndex 等方法,涵蓋大部分 LINQ 功能。本文示範如何在 Array.prototype 上補充 select, where, orderBy, groupBy, distinct, union, take, skip, first 等 LINQ 風格別名與進階查詢方法,打造流暢鏈式 API。

核心擴充模式

// 基礎:Select = map
Array.prototype.select = Array.prototype.map;

// Where = filter
Array.prototype.where = Array.prototype.filter;

// Take / Skip
Array.prototype.take = function(n) { return this.slice(0, n); };
Array.prototype.skip = function(n) { return this.slice(n); };

// First / FirstOrDefault
Array.prototype.first = function(predicate, defaultValue) {
  if (!predicate) return this[0] ?? defaultValue ?? null;
  for (const item of this) if (predicate(item)) return item;
  return defaultValue ?? null;
};

// Distinct(支援自訂比較器)
Array.prototype.distinct = function(comparer) {
  const result = [];
  const equals = comparer || ((a, b) => a === b);
  for (const item of this) {
    if (!result.some(r => equals(r, item))) result.push(item);
  }
  return result;
};

// Union = concat + distinct
Array.prototype.union = function(other) {
  return this.concat(other).distinct();
};

// OrderBy / ThenBy
Array.prototype.orderBy = function(selector, comparer) {
  const arr = [...this];
  const cmp = comparer || ((a, b) => a > b ? 1 : a < b ? -1 : 0);
  arr.sort((a, b) => cmp(selector(a), selector(b)));
  arr.thenBy = function(s, c) { /* 串聯排序邏輯 */ return this; };
  return arr;
};

// GroupBy:回傳 { key, items[] } 陣列
Array.prototype.groupBy = function(selector, comparer) {
  const groups = [];
  const eq = comparer || ((a, b) => a === b);
  for (const item of this) {
    const key = selector(item);
    let group = groups.find(g => eq(g.key, key));
    if (!group) groups.push(group = { key, items: [] });
    group.items.push(item);
  }
  return groups;
};

使用範例

const users = [
  { name: 'Amy',  age: 28, dept: 'IT' },
  { name: 'Bob',  age: 32, dept: 'HR' },
  { name: 'Cindy', age: 25, dept: 'IT' },
  { name: 'David', age: 35, dept: 'Finance' }
];

// 鏈式查詢:IT 部門、年齡降冪、取前 2 名、只選名字
const result = users
  .where(u => u.dept === 'IT')
  .orderBy(u => -u.age)
  .take(2)
  .select(u => u.name);
// result: ['Amy', 'Cindy']

// 分組統計
const deptStats = users
  .groupBy(u => u.dept)
  .select(g => ({ dept: g.key, count: g.items.length, avgAge: g.items.reduce((s, u) => s + u.age, 0) / g.items.length }));

注意事項

  • 修改內建原型(Array.prototype)可能造成命名衝突、破壞 for...in 迭代、影響第三方庫,生產環境建議封裝為獨立工具函式或使用 Lodash / Ramda。
  • TypeScript 專案需補充型別宣告(interface Array<T> { select... })。
  • 效能敏感場合,避免鏈式產生大量中間陣列,可改用 reduce 單趟處理。

理解 LINQ 對應關係有助於跨語言開發,實務上推薦使用成熟函式庫而非自行擴充原型。

copyright © 萬盛學電腦網 all rights reserved