DanWahlin / Angular-JumpStart

Angular and TypeScript JumpStart example application

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sorting Service

aparnapatil01 opened this issue · comments

Hi Dan,

I am finding little difficult to understand the logic behind sorter service and it would be really great if you could help me to clear my doubts.

For quick reference I'am adding the below code -

sort(collection: any[], prop: any) {
    this.property = prop;
    this.direction = (this.property === prop) ? this.direction * -1 : 1;

    collection.sort((a: any, b: any) => {
        let aVal: any;
        let bVal: any;

        if(prop && prop.indexOf('.') > -1) {
            aVal = PropertyResolver.resolve(prop, a);
            bVal = PropertyResolver.resolve(prop, b);
        } else {
            aVal = a[prop];
            bVal = b[prop];
        }

        if(this.isString(aVal)) { aVal = aVal.trim().toUpperCase(); }

        if(aVal === bVal) {
            return 0;
        } else if (aVal > bVal) {
            return this.direction * -1;
        } else {
            return this.direction * 1;
        }
    });
}
  1. I know the logic of sort function like if it returns 0 do nothing, 1 - Swap, Negative - continue, but I can't understand How this.direction variable is used to achieve this?. From the wordings it seems like it tracks the order(ascending or descending). What does this code line do, this.direction = (this.property === prop) ? this.direction * -1 : 1;

  2. Only one value ie: aVal is Upper Cased and not bVal. Could you please help me to understand?

--
Thanks

Hi! This isn't something normally addressed in Github issues since it's more of a question for StackOverflow.com, but I'm happy to give you a quick synopsis.

  1. The direction variable just swaps -1 to 1 or 1 to -1 to switch the sort direction.
  2. I don't remember why I only uppercased aVal...probably unique to the data at one point. You can experiment with taking that out to see any affect.

Hi Dan,

Okay. Thank You so much. I liked the code you wrote a lot. I can read your code, the code is so clean, every possible checks are done, modular and logical. As the project grows, the complexity increases, but in this project everything is so well-managed. I am learning a lot from this project and I would like to say thanks to you from the bottom of my heart.

--
Thanks

Thanks - that's very nice of you to say. I'm glad to hear the code has been helpful. Best of your luck with your projects!

Hi Dan, Thank you so much. :)