UNPKG

commadus

Version:

Elegantly formats lists with proper punctuation, including support for the Oxford comma.

69 lines (64 loc) 2.28 kB
/* ******************************************************* * commadus * * @license * * Apache-2.0 * * Copyright 2015-2025 Alex Stevovich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @meta * * package_name: commadus * file_name: src/index.js * purpose: Core functionality and exports combined. * * @system * * generated_on: 2025-03-15T00:36:05.028Z * certified_version: 1.0.0 * file_uuid: bba85a1e-47ba-4f04-aba2-d7804cd70ee5 * file_size: 2219 bytes * file_hash: 71e2b34d467ed430c2c68361b9593663c899308dcf9aa16261fa8c2d499d2662 * mast_hash: fcb1c9b1ba414aacae518a2de869200293f41d188f30d4deb089f889db08d3b2 * generated_by: preamble on npm! * * [Preamble Metadata] ********************************************************/ /** * Formats an array of items into a comma-separated list with an optional Oxford comma. * * @param {string[]} items - The list of items to format. * @param {Object} options - Formatting options. * @param {boolean} [options.oxford=true] - Whether to use the Oxford comma. * @returns {string} - The formatted list. * * @example * serialComma(["apple", "banana", "cherry"]); // "apple, banana, and cherry" * serialComma(["apple", "banana", "cherry"], { oxford: false }); // "apple, banana and cherry" */ function list(items, { oxford = true } = {}) { if (!Array.isArray(items)) { throw new TypeError('Expected an array of items.'); } if (items.length === 0) return ''; if (items.length === 1) return items[0]; if (items.length === 2) return items.join(' and '); const arr = [...items]; // Clone array to prevent mutation const lastItem = arr.pop(); const comma = oxford ? ',' : ''; return `${arr.join(', ')}${comma} and ${lastItem}`; } export default list;