aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMarak <[email protected]>2021-10-18 21:46:21 -0400
committerGitHub <[email protected]>2021-10-18 21:46:21 -0400
commit2b7ce5fbfe569a2328b520ad8f804c943f6140cb (patch)
tree7434d7bb7f134a306084009ffb93c7328330b6f7 /lib
parentad303baff670ef1842dc0a06d2f6a254591289b5 (diff)
parent5280f7bfec0ebe0af4e9e7f611c9b30a7c819867 (diff)
downloadfaker-2b7ce5fbfe569a2328b520ad8f804c943f6140cb.tar.xz
faker-2b7ce5fbfe569a2328b520ad8f804c943f6140cb.zip
Merge pull request #1177 from hsw107/master
feat: add uniqueArray helper function
Diffstat (limited to 'lib')
-rw-r--r--lib/helpers.js29
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/helpers.js b/lib/helpers.js
index 68e895e7..4ecdaab3 100644
--- a/lib/helpers.js
+++ b/lib/helpers.js
@@ -216,6 +216,35 @@ var Helpers = function (faker) {
};
/**
+ * 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
*
* @method faker.helpers.mustache