vendredi 20 décembre 2019

JavaScript codewars solution passing local node jest tests, but doesn't pass tests on codewars

this is my first stackoverflow post... so here goes!

I have written the following code for a codewars 5kyu challenge "Closest and Smallest": https://www.codewars.com/kata/5868b2de442e3fb2bb000119

I'm using jest in node to test it locally - and it is all working fine. But it's not passing the tests on Codewars. I would really appreciate any tips on this. thanks!

function closest(string) {
    if (string.length < 1) return [];
    const nums = string.split(" ");
    const weights = nums.map(e => e.split('').reduce((p, a) => Number(p) + Number(a)));
    const indexedWeights = [];
    let indexCounter = 0;
    for (let w of weights) indexedWeights.push([w, indexCounter++, Number(nums.shift())])
    let collected = [];
    indexedWeights.forEach(iw => {
        const iWCopy = indexedWeights.filter(item => item !== iw);
        const closest = iWCopy.reduce((a, b) => Math.abs(b[0] - iw[0]) < Math.abs(a[0] - iw[0]) ? b : a);
        const diff = Math.abs(closest[0] - iw[0]);
        collected.push([diff, iw[0], iw[1], iw[2]]);
    });
    collected.sort((a, b) => a[0] - b[0])
    const lowestDiff = collected[0][0]
    const result = collected.filter(n => n[0] === lowestDiff)
    result.sort((a, b) => a[1] - b[1])
    return [result[0].splice(1, 4), result[1].splice(1, 4)];
}

Test:

const closest = require("../5kyu_challenges/closestAndSmallest");

describe("closest", () => {

    test("returns an array containing 2 sub-arrays which consist of 3 numbers representing closest and smallest numbers", () => {
        expect(closest("")).toEqual([]);
        expect(closest("456899 50 11992 176 272293 163 389128 96 290193 85 52")).toEqual([ [13, 9, 85], [14, 3, 176] ]);
    });

    test("sorts by index number if weights are equal", () => {
        expect(closest("239382 162 254765 182 485944 134 468751 62 49780 108 54")).toEqual([ [8, 5, 134], [8, 7, 62] ]);
        expect(closest("403749 18 278325 97 304194 119 58359 165 144403 128 38")).toEqual([ [11, 5, 119], [11, 9, 128] ]);
    });

});

Aucun commentaire:

Enregistrer un commentaire