DEV Community

Pavel Ravits
Pavel Ravits

Posted on

Iterating on gpt-4 code suggestions

AI can give you what you want, but you should know what you want to achieve anyway.

js
given array A and array B
B is array with objects like {id:string}
write a function which gets - A, changed-B, and previous-B , detects items reorder in B and applies that on 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
}
Enter fullscreen mode Exit fullscreen mode

now write that in a more functional style

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)])
}
Enter fullscreen mode Exit fullscreen mode

use Map constractor

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)])
}
Enter fullscreen mode Exit fullscreen mode

implement this in one line

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

use one line implementation using findIndex

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

So progressively we got one line instead of 10 and only one implementation was non working


And the final implementation:

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

Top comments (0)