DEV Community

Cover image for Shortest js compare function, by 6 AI machines
Ellis
Ellis

Posted on • Edited on

Shortest js compare function, by 6 AI machines

I asked 6 different AI machines

I want a shortest possible javascript function. Input parameters: a and b (both can be of any type). Output: if a < b then return an arbitrary negative number, if a > b then return an arbitrary positive number, if a equals b then 0.

(This is a standard, very common "compare" function. We typically use it like: const sorted = array.toSorted(compare);

-- Date: 7 Oct 2024.
-- All using unpaid versions as available on the internet.
-- Only Claude required a login.

Google Gemini, MS Copilot, Phind, Perplexity, Claude all produced the same result:
(a, b) => a < b ? -1 : a > b ? 1 : 0

Only "Chatgpt 4o mini" produced:
(a, b) => (a > b) - (a < b)

(The first one is commonly known. The reason I asked this question in the first place: this common one has always looked a bit cluttery/clunky to me. As for the second one, I'd be interested to know if anyone has every heard of it. The first one has: 13 elements, the second one: 7 elements, by one way of counting.)

 

Afterwards I asked Chatgpt

Which of the above functions will execute faster in real time?

It answered:

  • Number of comparisons: f1 always performs two comparisons regardless of the input. f2 may perform only one comparison if the first condition (a < b) is true.
  • Operation cost: Both functions return a small, constant amount of data, but the arithmetic in f1 involves a subtraction, which could be slightly more expensive than just returning a value directly.
  • Conclusion: In most cases, f2 would be faster due to potentially needing only one comparison and avoiding the subtraction operation.

 

My conclusion

This suggests to me that, within the limits of this small experiment, "ChatGPT 4o mini" distinguishes itself from the other five with a more capable and deeper calculation power.

 

Benchmark

I wrote a js program to compare the sorting times on a shuffled array of the integers 1 to 100,000,000. I ran the program a number of times with Node on Windows. The result suggests an equal speed. (The difference is in the order of 1%.)

Top comments (0)