迭代 gpt-4 代码建议

73 阅读1分钟

人工智能可以给你你想要的,但无论如何你都应该知道你想要实现什么。

js
给定数组 A 和数组 B
B 是包含 {id:string} 之类对象的数组
编写一个函数,它获取 - A、changed-B 和 previous-B,检测 B 中的项目重新排序并将其应用于 a

function applyReorder(a, prevB, changedB) {
    // Create a map of id to index for the previous b array
    const prevBIndexMap = new Map()
    prevB.forEach((item, index) => {
        prevBIndexMap.set(item.id, index)
    })
    // Create a reordered array based on the changedB array
    const reorderedA = new Array(a.length)
    changedB.forEach((item, index) => {
        const prevIndex = prevBIndexMap.get(item.id)
        reorderedA[index] = a[prevIndex]
    })
    return reorderedA
}

现在以更实用的风格来写

function applyReorder(a, prevB, changedB) {
    const prevBIndexMap = prevB.reduce((map, item, index) => {
        map.set(item.id, index)
        return map
    }, new Map())
    return changedB.map((item) => a[prevBIndexMap.get(item.id)])
}

使用地图构造器

function applyReorder(a, prevB, changedB) {
    const prevBIndexMap = new Map(
        prevB.map((item, index) => [item.id, index])
    )
    return changedB.map((item) => a[prevBIndexMap.get(item.id)])
}

在一行中实现这一点

const applyReorder = (a, prevB, changedB) =>
    changedB.map(
        (item) =>
            a[
                new Map(prevB.map((el, idx) => [el.id, idx])).get(
                    item.id
                )
            ]
    )

使用 findIndex 使用一行实现

const applyReorder = (a, prevB, changedB) =>
    changedB.map(
        (item) => a[prevB.findIndex((el) => el.id === item.id)]
    )

所以逐渐地我们得到了一行而不是 10 行,只有一个实现不起作用


最后的实现:

function applyReorder(
    applyTo: any[],
    prevAccordingTo: { id: string }[],
    changedAccordingTo: { id: string }[]
) {
    return changedAccordingTo.map(
        (item) =>
            applyTo[
                prevAccordingTo.findIndex((el) => el.id === item.id)
            ]
    )
}