teun / thenby.js Goto Github PK
View Code? Open in Web Editor NEWthenBy is a javascript micro library that helps sorting arrays on multiple keys
License: Apache License 2.0
thenBy is a javascript micro library that helps sorting arrays on multiple keys
License: Apache License 2.0
The fork https://www.npmjs.com/package/thenby is old and doesn't even have a module.exports
. I really like this micro library and would like to use it. Could you publish it on npm? You could use firstby-thenby
as name.
Usually from high to low,An empty string (" ").In general, should be at the bottom,
Hello. I like of how thenBy() works and I like to reimplements it on a PHP. So I want to know if I can do it based on your concept. It should be called VanillaSort, because I'm working on a big package called Vanilla: https://bitbucket.org/rentalhost/
Thank you for this library, I've been using it quite a bit. Came across a sorting problem when sorting number values above 2 digits, it sorts 99 and below first only taking into account the first digit. Below is an example ordered ascending, it goes 10, 100, 101, etc for ordering.
The built-in string compare logic of Intl.Collator should theoretically be better than our somewhat naive a > b
and .toUpperCase()
. But:
ignoreCase:true
?Hi, I'm implementing thenBy.js library in my polymer application by using the event listener.
However, the sort method not update when the data changed. But the console output 'test'.
How can I implement the event listener to this library?
this.addEventListener('data-changed', (e) => this.sortOrderList(this.orderItems))
sortOrderList(order) {
console.log('test')
// SORT BY EDD THEN BY SPT
let s = firstBy(function (v1, v2) { return v1.order_delivery - v2.order_delivery; })
.thenBy(function (v1, v2) { return v1.order_duration - v2.order_duration; });
this.sortedOrder = order.sort(s);
return order.sort(s);
}` ``
For example,
sort(firstBy( function(item) { return item.value(); } ))
would be equivalent to the currently supported
sort(firstBy( function(item1, item2) {return item1.value() - item2.value(); } ))
I think Function.prototype.length
can be used to detect if a unary function is passed.
Hi, maybe I am missing something but I could not get my array to sort using the example you provided. I also saw the fiddle you posted on a stackoverflow answer but the result over there is also not sorted (http://jsfiddle.net/n4ncq2nc/1/). Thanks
Exist a way to consider dot instead of comma?
I wish to use this in a project - hence I wanted this to be tagged.
An array of object needs to be sorted by organizer=me
first, and then by order
property.
It seems to me that thenBy
is not getting triggered.
I've created a Fiddle from one of the similar Fiddles found here, please open the console to see that indeed "Not even run" is not showing up:
http://jsfiddle.net/u8n430rp/1/
Hello Teun,
thanks for this great and lightweight lib. Unfortunately I'm running into issues when not immediately chaining thenBy in the same call. E.g.
sort_stack = undefined;
sort_stack = firstBy(some_func);
sort_stack.thenBy(some_func);
some_array.sort(sort_stack);
In this case the thenBy is never executed. In my scenario I have a variable number of sort fields in an array and need to create multiple thenBy dynamically. Any idea how to do that?
BR,
toovy
It would be interesting to see this library ES6 compliant and working with TypeScript.
That's a beginning of a declaration:
interface ThenBy {
thenBy(fnc: ((v1, v2) => number) | string, direction?: number): ThenBy;
thenBy(propertyName: string, direction?: number): ThenBy;
(fnc: (v1, v2) => number);
}
function firstBy<T>(fnc: (v1: T, v2: T) => number, direction ?: number): ThenBy;
function firstBy<T>(propertyName: keyof T, direction ?: number): ThenBy;
Sorry about being pedantic - I really like what you've done! Nice work!
Could you put a license on it, such as MIT [1] or other open source license, so I know if I can use it? Thanks so much!
This is more to do with the node fork but there's no issue tracker...
ping @rodriguezartav
Hi I cannot make it work after the first condition.
`
this.itemsCollection.sort(
firstBy(function(a: ItemDto, b: ItemDto) {
console.log('first')
return a.title.length - b.title.length
})
.thenBy(function(a: ItemDto, b: ItemDto) {
console.log('second')
return a.text.length - b.text.length
})
.thenBy(function(a: ItemDto, b: ItemDto) {
console.log('third')
return a.itemId - b.itemId
})
)
`
It works well for the first block but not for the others. What I am doing wrong? Thanks
Hi Like the library any chance you could add a licence to it, such as MIT or one of the other permissive licences. Makes it easier to use your code if your working on larger open source projects where licences of are tracked and monitored.
Hi,
Been using thenBy for a few weeks now and I like it alot. It simply works. I'm in a bit of a stump though trying to figure out if a specific sort is possible with this module.
I have records displayed in a table which have attributes: priority of 0 - 2 (2 being most important), person status of 0 - 4, wait time, and total time.
I'm trying to sort this information (in tiers if you will) like so:
No biggie if this isn't possible. Just curious. Thanks!
When using the custom compare demo code given, TypeScript throws an error.
const cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
var cardCompare = (c1, c2) =>{
return cards.indexOf(c1) - cards.indexOf(c2);
}
var handOfCards = [
{ id: 7, suit:"c", card:"A" },
{ id: 8, suit:"d", card:"10" },
// etc
];
handOfCards.sort(firstBy("card", {cmp: cardCompare, direction: "desc"}));
ERROR in src/app/opcenter/personnelfiles/personnelfiles.component.ts(103,27): error TS2345: Argument of type '{ cmp: (c1: any,
c2: any) => number; }' is not assignable to parameter of type '1 | "desc" | -1 | opt | "asc"'.
Object literal may only specify known properties, and 'cmp' does not exist in type 'opt'.
I have literally done nothing other than copy the demo code. There seems to be an issue going on here.
With typescript (v3.8.3), the compiler tells me that the second parameter of the key-param on firstBy/thenBy (i.e.: "v2") might be undefined... which just isn't true if using the (a,b)=> number
form.
Imho these typings should provide a better user-experience while stille sticking to your spec:
export function firstBy<T = any>(key: ((v1: T, v2: T) => any), direction?: number | opt): IThenBy<T>;
export function firstBy<T = any>(key: ((v1: T) => any), direction?: number | opt): IThenBy<T>;
export function firstBy<T = any>(key: (keyof T), direction?: number | opt): IThenBy<T>;
// catch all implementation. Might perhaps be omitted for clarity.
export function firstBy<T = any>(key: ((v1: T, v2?: T) => any) | keyof T, direction?: number | opt): IThenBy<T>;
Please explain how to call it with Typescript in a more detailed way.
What i have tried:
I have added the files to my project and made the import statement.
import {firstBy} from "thenby";
How do i instantiate it/ call it now? I always get an undefined for firstBy. I have tried multiple ways but none of them worked.
An example would be great.
Thank you in advance. Great work!
Hello guys, this may not be an issue, but there's little info out there. How do I add it into Angular 2/4 ?
I have been able to successfully use the thenBy library in a Vue file like so -
Official Scenarios Vue file:
<template>
<div>
{{ sortedOfficialScenarios }}
</div>
</template>
<script>
import { firstBy } from 'thenby';
export default {
data () {
return {
officialScenarios: []
}
},
methods: {
async getOfficialScenarios() {
this.officialScenarios = await this.$service.access('officialScenarios').get();
}
},
created: function () {
this.getOfficialScenarios();
},
computed: {
sortedOfficialScenarios() {
return (this.officialScenarios).slice().sort(
firstBy(function (a) { return a.year }, -1)
.thenBy('created', -1)
);
}
}
}
</script>
thenBy is a useful library for this project so I'd like to include it globally to avoid having import statements in each Vue file. However, this is where I'm stuck. In main.js I've tried:
import { firstBy } from 'thenby';
Vue.use(firstBy);
With that code in place, and the import { firstBy} from 'thenby';
disabled in the Official Scenarios file, an error is displayed in the console that says Error in render: "ReferenceError: firstBy is not defined". I have also tried this in main.js:
import { firstBy } from 'thenby';
new Vue({
router,
firstBy,
render: h => h(App)
}
}).$mount('#app');
The error message is the same as above.
Is there a way to use thenBy globally in Vue? If so, how?
So I'm using redux, and in my store I store the rows of my table like this:
jobs: {
byJobId: {}, //Objects indexed by id
allJobIds: [] //Array of ids to indicate sorting order
},
Is it possible to use this library to sort the array based on the object via its id?
It would be REALLY nice if there was a way to sort strings numerically instead of lexicographically. A stackoverflow post like the following shows how to do it with arrays. Could this be added?
https://stackoverflow.com/questions/8107226/how-to-sort-strings-in-javascript-numerically
There's a more or less official list of license names/abbreviations: https://spdx.org/licenses/
This list ist used by some tools (e.g.: license-checker) to do some useful stuff.
I propose changing the "license" entry in package.json from "Apache 2.0" to "Apache-2.0" according to SPDX.
Hi,
at https://github.com/Teun/thenBy.js/blob/master/thenBy.js#L16 the firstBy is not declared with var.
This is a problem when using strict mode, it triggers an error
thanks
What always strikes me as a bit annoying are the magic numbers for 1/-1 for up/down.
Most programming docs refer to sorting directions as "ascending" or "descending or asc/desc for short.
Might be cool to have direction/options support this as well, resulting in something like:
type SortOrder = -1 | 1 | 'asc' | 'desc';
export function firstBy(key: (v1: T, v2: T) => any), direction?: SortOrder | opt): IThenBy;
firstBy() has correctly infered type on params (a,b) but when i chain it with .thenBy() it suddenly stops infering (a, b) and goes as unknown.
Does anybody else experience that? TS: v4.4.3
I'll try attach POC in codepen later.
I tried to rewrite your wonderful script as a es6 module (export thenBy ...
and import thenBy from ...
), but I fail shamefully. So I wonder if there is a chance to motivate you to provide a script that follows that convention?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.