From b415fa9747085915907c70b3d9399df64f3729c8 Mon Sep 17 00:00:00 2001 From: paige <88659700+paishee@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:36:35 -0600 Subject: [PATCH] Create sortBy.js --- src/Soup/functions/sortBy.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/Soup/functions/sortBy.js diff --git a/src/Soup/functions/sortBy.js b/src/Soup/functions/sortBy.js new file mode 100644 index 0000000..ba62720 --- /dev/null +++ b/src/Soup/functions/sortBy.js @@ -0,0 +1,30 @@ +const Soup = require('../index.js'); + + +function SoupSortBy(obj, compare=null) { + if (!obj.type) obj = Soup.from(obj); + obj = obj.copy(); + var copy = this.copy(); + + var stuff = []; + + obj.sort( (rawA, rawB) => { + let a = (typeof rawA == "string") ? rawA.toUpperCase().localeCompare(rawB) : rawA; + let b = (typeof rawB == "string") ? rawB.toUpperCase().localeCompare(rawA) : rawB; + + stuff.push( [a, b] ); + + return (compare) ? compare(a, b) : a - b; + }); + + var i = 0; + + return new copy.constructor(copy.sort( (_a, _b) => { + let [a, b] = stuff[i]; i++; + + return (compare) ? compare(a, b) : a - b; + })); +} + + +Soup.newF("sortBy", SoupSortBy);