Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/utils-as-array-falsy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solid-primitives/utils": patch
---

Fix `asArray` dropping falsy values that are not nullish: `asArray(0)`, `asArray("")` and `asArray(false)` returned `[]` instead of `[0]`, `[""]` and `[false]`.
2 changes: 1 addition & 1 deletion packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export const access = <T extends MaybeAccessor<any>>(v: T): MaybeAccessorValue<T
typeof v === "function" && !v.length ? v() : (v as any);

export const asArray = <T>(value: T): (T extends any[] ? T[number] : NonNullable<T>)[] =>
Array.isArray(value) ? (value as any) : value ? [value as any] : [];
Array.isArray(value) ? (value as any) : value != null ? [value as any] : [];

/**
* Access an array of MaybeAccessors
Expand Down
32 changes: 31 additions & 1 deletion packages/utils/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { describe, test, expect, assert, vi } from "vitest";
import { handleDiffArray, arrayEquals, createHydratableSignal, withAccess } from "../src/index.js";
import {
handleDiffArray,
arrayEquals,
asArray,
createHydratableSignal,
withAccess,
} from "../src/index.js";

describe("handleDiffArray", () => {
test("handleAdded called for new array", () => {
Expand Down Expand Up @@ -124,3 +130,27 @@ describe("withAccess", () => {
expect(fn).not.toHaveBeenCalled();
});
});

describe("asArray", () => {
test("wraps single values", () => {
expect(asArray("a")).toEqual(["a"]);
const obj = {};
expect(asArray(obj)).toEqual([obj]);
});

test("keeps arrays as they are", () => {
const arr = [1, 2];
expect(asArray(arr)).toBe(arr);
});

test("keeps falsy values that are not nullish", () => {
expect(asArray(0)).toEqual([0]);
expect(asArray("")).toEqual([""]);
expect(asArray(false)).toEqual([false]);
});

test("returns an empty array for undefined and null", () => {
expect(asArray(undefined)).toEqual([]);
expect(asArray(null)).toEqual([]);
});
});
Loading