Skip to content

Commit

Permalink
Update: Allow first() to accept a single-item array (fixes #26)
Browse files Browse the repository at this point in the history
  • Loading branch information
nzakas committed Apr 15, 2021
1 parent 84c64b1 commit 6c8b62b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
5 changes: 3 additions & 2 deletions src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,12 @@ export class Env {
* @param {string} [defaultValue] The default value to return if the
* environment variable is not found.
* @returns {string|undefined} The environment variable value if found or undefined if not.
* @throws {TypeError} If keys is not an array with at least one item.
*/
first(keys, defaultValue) {

if (!Array.isArray(keys) || keys.length < 2) {
throw new TypeError("First argument must be an array of two or more strings.");
if (!Array.isArray(keys) || keys.length < 1) {
throw new TypeError("First argument must be an array of one or more strings.");
}

for (const key of keys) {
Expand Down
12 changes: 9 additions & 3 deletions tests/env.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,22 @@ describe("Env", () => {

});

it("should throw an error when the first argument doesn't have at least two items", () => {
it("should throw an error when the first argument doesn't have at least one item", () => {
const env = new Env(source);

assert.throws(() => {
env.first(["USERNAME"]);
env.first([]);
}, /First argument/);

});

it("should get the first environment variable when it exists", () => {
it("should get the first environment variable when one exists", () => {
const env = new Env(source);
const value = env.first(["USERNAME"]);
assert.strictEqual(value, source.USERNAME);
});

it("should get the first environment variable when only one exists", () => {
const env = new Env(source);
const value = env.first(["USERNAME", "ALT_USERNAME"]);
assert.strictEqual(value, source.USERNAME);
Expand Down

0 comments on commit 6c8b62b

Please sign in to comment.