【问题标题】:faker.helpers.unique(faker.datatype.number, options) does NOT honor submitted optionsfaker.helpers.unique(faker.datatype.number, options) 不接受提交的选项
【发布时间】:2023-02-07 09:27:31
【问题描述】:

客观的

我想使用 @faker-js/faker's helpers.unique() function 生成具有指定最小值和最大值的唯一整数数组。根据他们的文档,我应该能够执行以下操作:

// import faker
import { faker } from '@faker-js/faker'

// extract the functions I plan to use (to make the next part more readable)
const { helpers: { unique }, datatype: { number } } = faker

// create array of 10 `undefined` elements and replace them with unique numbers
const numbers = Array.from({ length: 10 }).map(() => unique(number, { min: 1, max: 10 }))

// EXPECTED output
console.log(numbers) // [5, 2, 4, 10, 8, 9, 1, 7, 3, 6]

// ACTUAL output
console.log(numbers) // [17530, 15198, 10760, 38070, 84874, 89011, 4254, 43244, 21142, 79435]

我试过的

以下是我试图弄清楚发生了什么的各种尝试:

// actual output same as above
const options = { max: 10, min: 1 } // save options in a var in same order as docs
const numbers = Array.from({ length: 10 }).map(() => unique(number, options))

// try submitting options as separate params => ERROR (as expected)
const numbers = Array.from({ length: 10 }).map(() => unique(number, 10, 1))

// calling OUTSIDE of the `map()` function
unique(f.datatype.number, {min: 1, max: 10}) // yields e.g. 47858

// calling just `number()` to make sure it honors options if called normally
number({ min: 1, max: 10 }) // correctly returns integers between 1 and 10

此外,在@faker-js/faker repo 上搜索“unique”,发现截至 2023 年 1 月 27 日(上周撰写本文时)the helpers.unique() function is slated for deprecation in v8.x

我将把这个问题留在这里,因为它已经写好了并且有人可能知道答案,并且它可能对继续使用 <= v7.6 的人有用。

【问题讨论】:

    标签: javascript faker.js


    【解决方案1】:

    想出了另一种方法来做到这一点:

    const numbers = Array.from({ length: 10 }).map(() => unique(() => number({min: 1, max: 10})))
    

    这对我来说不是一种直观的方法,但它确实有效。

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2017-09-22
      • 2010-10-11
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多