1
\$\begingroup\$

I have a data table with 7 columns. The first column is the index that increases from 1 to N and is considered to be in ascending order by default. The remaining columns are unsorted. I need to be able to show icons on the table depending on the type of sorting performed, an up arrow for a column in ascending order, a down arrow for a column in descending order and no arrows in unsorted mode.

I assume that when a person sorts column 2, column 1 enters the unsorted state while column 2 can be in an ascending or descending sorted state. I need a 3 way switch where 1 variable at a given time can be toggled ascending or descending and the rest of them are reset back to their initial values.

I wrote a class to handle this and would love to know your opinion on the same. Would this be the RIGHT way to handle 3 way switch between a group of variables? Are there any better approaches for the same.

class SortState {
    constructor(options = {}) {
        this.unsorted = 0
        this.ascending = -1
        this.descending = 1
        this.state = []
        this.initialValues = []
        if (options.keys && options.keys.length && options.values && options.values.length) {

            for (let i = 0, j = 0; i < options.keys.length && j < options.values.length; i++ , j++) {
                this.state.push({
                    key: options.keys[i],
                    value: options.values[j]
                })
            }

            this.initialValues = options.values
        }
    }

    toggle(key) {
        let found = this.state.find(i => i.key === key)
        if (found) {
            let length = this.state.length, current
            for (let i = 0; i < length; i++) {
                current = this.state[i]
                if (current.key === key) {
                    if (current.value === this.ascending) {
                        current.value = this.descending
                    }
                    else if (current.value === this.descending) {
                        current.value = this.ascending
                    }
                    else {
                        current.value = this.initialValues[i]
                    }
                }
                else {
                    current.value = this.unsorted
                }
            }
        }
    }

    getKey(key) {
        let found = this.state.find(i => i.key === key)
        return found ? found : null
    }
}
\$\endgroup\$
0

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.