Untitled

 avatar
unknown
plain_text
5 months ago
1.8 kB
4
Indexable
/**
 * Spread Sheet Service
We are creating a service which will handle basic capabilities of an excel sheet. As a user I should be able to set any value to the cell and get 
that value back. I should also be able to set a formulae into the cell and then return back the computed value. Create the following methods to 
support the above

====== SetCell() ======
====== GetCell() =====

Make sure the code is working at the end with all test cases covered. Keep in mind that there is no third party interactio
 */


class SpreadSheet {
    constructor() {
        this.SpreadSheet = {};
        this.formula = {}
    }

    SetCell(r, c, value) {
        let cellId = c + r;
        if (isNaN(value)) {
            /**A+B+C 
             * C1 = A+B
            */
            let formula = value
            value = this.findCalculation(formula, cellId)
        }

        this.SpreadSheet[cellId] = { value: value, formula: value };
    }

    GetCell(r, c) {
        let cellId = c + r;;
        let valObj = this.SpreadSheet[cellId];
        console.log(`current cell value of ${cellId} is ` + valObj.value)
        return valObj.value;
    }

    findCalculation(formula, cell1) {
        let dataArr = formula.split("");
        let expression = ``;
        dataArr.map((cellId) => {
            if (cellId.match(/[A-Z]/)) {
                this.formula[cellId + 1] = cell1;
            } else if (!cellId.match(/[0-9]/)) {
                let getObject = this.SpreadSheet[cellId];

                expression += getObject?.value?.toString() || 0;
            }

        })
    }
}



let spreadSheet = new SpreadSheet();


spreadSheet.SetCell(1, 'A', 20);
spreadSheet.SetCell(1, 'B', 30);

spreadSheet.GetCell(1, 'A');
spreadSheet.GetCell(1, 'B');


spreadSheet.SetCell(1, 'C', `A1+B1`);
Editor is loading...
Leave a Comment