JenMorgan / js-learning

0 stars 0 forks source link

Write a JS function to divide all numeric properties in 2. #36

Open JenMorgan opened 4 years ago

JenMorgan commented 4 years ago
let salaries = {
    John : 100,
    Ann : 160,
    Pete : 130,
}

let cafe = {
    age : "20",
    name: "John",
    salary : 2400,
}

function createHalfValuesCopy (obj) {
    let copy = {};
    for (let key in obj) {
      copy[key] = divideInTwoOrReturnOrigin(obj[key]);
    }
    return copy;
  }

function divideInTwoOrReturnOrigin (number) {
    if (typeof number === 'number') {
        return number / 2;
    }
    return number;
}
JenMorgan commented 4 years ago
describe ("createHalfValuesCopy", function() {
    it("should divide numeric properties in 2 in the object", function() {
        const salary = {
            John : 50,
            Ann : 80,
            Pete : 65,
        }
        assert.deepEqual(createHalfValuesCopy(salaries), salary);
    });

    it("should do nothing if property is not a number", function() {
        const secondObj = {
            age : "20",
            name: "John",
            salary : 1200,
        }
        assert.deepEqual(createHalfValuesCopy(cafe), secondObj);
    });
});

describe ("divideInTwo", function() {
    it("should divide in 2", function() {
        assert.equal(divideInTwoOrReturnOrigin(4), 2);
        assert.equal(divideInTwoOrReturnOrigin(10), 5);
        assert.equal(divideInTwoOrReturnOrigin(15), 7.5);
    });
    it("should return the value if not the number", function() {
        assert.equal(divideInTwoOrReturnOrigin(true), true);
        assert.deepEqual(divideInTwoOrReturnOrigin([]), []);
        assert.equal(divideInTwoOrReturnOrigin("string"), "string");
    });
});