From 5280f7bfec0ebe0af4e9e7f611c9b30a7c819867 Mon Sep 17 00:00:00 2001 From: Hanna Walter Date: Fri, 28 May 2021 12:32:17 -0600 Subject: feat: add uniqueArray helper function --- lib/helpers.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'lib') diff --git a/lib/helpers.js b/lib/helpers.js index 68e895e7..4ecdaab3 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -215,6 +215,35 @@ var Helpers = function (faker) { return o; }; + /** + * takes an array of strings or function that returns a string + * and outputs a unique array of strings based on that source + * @example uniqueArray(faker.random.word, 50) + * @example uniqueArray(faker.definitions.name.first_name, 6) + * @example uniqueArray(["Hello", "World", "Goodbye"], 2) + * @method faker.helpers.uniqueArray + * @param {string[] | function => string} source + * @param {number} length + * @returns {string[]} + */ + self.uniqueArray = function(source, length) { + if (Array.isArray(source)) { + const set = new Set(source); + const array = Array.from(set); + return faker.helpers.shuffle(array).splice(0, length); + } + const set = new Set(); + try { + if (typeof source === "function") { + while (set.size < length) { + set.add(source()); + } + } + } finally { + return Array.from(set); + } + }; + /** * mustache * -- cgit v1.2.3