Skip to content

Commit 709703f

Browse files
committed
feat: ensureArray
1 parent 62f5366 commit 709703f

File tree

5 files changed

+48
-1
lines changed

5 files changed

+48
-1
lines changed

.mocharc.json

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"require": "ts-node/register,source-map-support/register",
33
"watch-extensions": "ts",
4+
"watch-files": "src/**/*.ts, test/**/*.ts",
45
"recursive": true,
56
"reporter": "spec",
67
"timeout": 5000

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414
],
1515
"scripts": {
1616
"build": "sf-build",
17+
"ci-docs": "yarn sf-ci-docs",
1718
"clean": "sf-clean",
1819
"clean-all": "sf-clean all",
1920
"compile": "sf-compile",
2021
"docs": "sf-docs",
21-
"ci-docs": "yarn sf-ci-docs",
2222
"format": "sf-format",
2323
"lint": "sf-lint",
2424
"lint-fix": "yarn sf-lint --fix",

src/collections.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/*
2+
* Copyright (c) 2022, salesforce.com, inc.
3+
* All rights reserved.
4+
* Licensed under the BSD 3-Clause license.
5+
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6+
*/
7+
8+
/**
9+
* Normalize an object to be an array if it isn't one.
10+
*
11+
* @param entryOrArray - An object that could be an array of its type or just its type
12+
* @returns An array of the input element (which might be empty)
13+
*/
14+
15+
export const ensureArray = <T>(entryOrArray: T | T[] | undefined): T[] => {
16+
if (entryOrArray) {
17+
return Array.isArray(entryOrArray) ? entryOrArray : [entryOrArray];
18+
}
19+
return [];
20+
};

src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@ export * from './env';
1111
export * from './errors';
1212
export * from './json';
1313
export * from './nodash';
14+
export * from './collections';

test/collections.test.ts

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* Copyright (c) 2022, salesforce.com, inc.
3+
* All rights reserved.
4+
* Licensed under the BSD 3-Clause license.
5+
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6+
*/
7+
import { expect } from 'chai';
8+
import { ensureArray } from '../src/collections';
9+
10+
describe('collections', () => {
11+
describe('ensureArray', () => {
12+
it('undefined => empty array', () => {
13+
const input = undefined;
14+
expect(ensureArray(input)).to.deep.equal([]);
15+
});
16+
it('an array => the array', () => {
17+
const input = ['a', 'b'];
18+
expect(ensureArray(input)).to.deep.equal(input);
19+
});
20+
it('a single item => obj in an array', () => {
21+
const input = 'a';
22+
expect(ensureArray(input)).to.deep.equal([input]);
23+
});
24+
});
25+
});

0 commit comments

Comments
 (0)