Skip to content

Instantly share code, notes, and snippets.

@Fedcomp
Last active April 30, 2021 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fedcomp/9c8a8f64b23047ac3e469fc3fcc92e1e to your computer and use it in GitHub Desktop.
Save Fedcomp/9c8a8f64b23047ac3e469fc3fcc92e1e to your computer and use it in GitHub Desktop.
Array comparison in php, javascript, and ruby
[
{ "name": "leroy", "kills": 25, "banned": false },
{ "name": "jenkins", "kills": 30, "banned": false },
{ "name": "cheater", "kills": 999, "banned": true },
{ "name": "n00b", "kills": 0, "banned": false }
]
$ php -v
PHP 7.4.16 (cli) (built: Mar  2 2021 10:35:27) ( ZTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.16, Copyright (c), by Zend Technologies

$ php process.php 
#1 jenkins
#2 leroy
$ node -v
v12.21.0

$ node process.js 
#1 jenkins
#2 leroy
$ ruby -v
ruby 2.6.6p146 (2020-03-31) [x86_64-linux]

$ ruby process.rb 
#1 jenkins
#2 leroy

I spent most of the time debugging php version, even consider i work with php everyday.

C (crap) for php readability, strong A for javascript and A+ for ruby. Ruby version explicitly split filtering in two parts for readability and because it's ruby way. It could be 1 line like for the other two.

I weren't using ruby for years, I use javascript from time to time, these two didn't take much time, unlike php version. If we add additional criteria, php will look even more ugly, while javascript and ruby versions will stay readable and good (did i tell you i hate javascript btw?)

api_call = require('./data.json')
api_call = api_call
.filter(p => p.kills > 0 && ! p.banned)
.sort((a, b) => a.name.localeCompare(b.name))
.forEach((player, position) => console.log(`#${position + 1} ${player.name}`))
<?php
$api_call = json_decode(file_get_contents('data.json'));
$ranked = array_filter($api_call, function($p) { return $p->kills > 0 && ! $p->banned; });
// Mutable arrays are crap
usort($ranked, function ($a, $b) { return $a->name <=> $b->name; });
foreach($ranked as $position => $player) { echo "#" . ($position + 1) . " {$player->name}\n"; }
require 'json'
api_result = JSON.parse(File.read('data.json'))
api_result
.select {|p| p['kills'].positive? }
.reject {|p| p['banned'] }
.sort_by {|p| p['name'] }
.each.with_index(1) {|player, position| puts "##{position} #{player['name']}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment