From 5f1eb229fe84dd80bee3ff6d65c14a58647405e3 Mon Sep 17 00:00:00 2001 From: JamieSlome Date: Mon, 28 Dec 2020 15:28:46 +0000 Subject: [PATCH] feat(add-object-property): new function with unit tests for adding a new property to an object --- index.js | 4 +++- test/polyfig.js | 15 +++++++++++++++ util/addObjectProperty.js | 28 ++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 util/addObjectProperty.js diff --git a/index.js b/index.js index 5e6359e..92c5f2a 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ const sortArrayByKey = require("./util/sortArrayByKey"); const mergeObjects = require("./util/mergeObjects"); const sizeOfObject = require("./util/sizeOfObject"); const onlyUniqueValues = require("./util/onlyUniqueValues"); +const addObjectProperty = require("./util/addObjectProperty"); module.exports = { removeFromString, @@ -21,5 +22,6 @@ module.exports = { sortArrayByKey, mergeObjects, sizeOfObject, - onlyUniqueValues + onlyUniqueValues, + addObjectProperty }; diff --git a/test/polyfig.js b/test/polyfig.js index 95eb6af..2c536b1 100644 --- a/test/polyfig.js +++ b/test/polyfig.js @@ -182,4 +182,19 @@ describe("polyfig", function () { outcome.should.eqls([1, 2, 3, "1", "3", "2"]); }); }); + + describe("addObjectProperty", function () { + it("should exist as a method", function () { + expect(polyfig.addObjectProperty).to.exist; + }); + + it("should add a new property to an object", function () { + let x = {}; + let y = "poly"; + let z = ["fig"]; + polyfig.addObjectProperty(x, y, z); + let outcome = x; + outcome.should.eqls({ poly: ["fig"] }); + }); + }); }); diff --git a/util/addObjectProperty.js b/util/addObjectProperty.js new file mode 100644 index 0000000..d72bf3d --- /dev/null +++ b/util/addObjectProperty.js @@ -0,0 +1,28 @@ +/** + * + * @name addObjectProperty + * + * @summary How do you add a key-value pair or new property to an object? + * + * @since 1.3.0 + * + * @category Object + * + * @param {Object} x - Object to add new property to + * @param {string} y - Property name + * @param {any} z - Property value + * + * @return {Object} Provided object with new property added + * + * @example + * => polyfig.addObjectProperty({}, "poly", ["fig"]); + * => {"poly": ["fig"]} + */ + +function addObjectProperty(x, y, z) { + return typeof x === "object" && x !== null && typeof y === "string" + ? (x[y] = z) + : new Error("x is not of type object or y is not of type string"); +} + +module.exports = addObjectProperty;