Final: port a queue model
Lesson 48 of 48 in Coddy's PHP for JavaScript Developers course.
Challenge
EasyInput is [initial,operations]. Port the source reference program supplied in this task. WorkQueue(initial array) stores string items. push(string):void appends; pop():?string removes and returns the oldest or null when empty; size():int counts remaining. Operations are [push,text] or [pop]. Driver prints popped values separated by commas, using EMPTY for null, then |size. Input items contain ASCII letters only.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit WorkQueue.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
JavaScript reference program
class WorkQueue {
constructor(initial) {this.items = [...initial];}
push(item) {this.items.push(item);}
pop() {return this.items.length ? this.items.shift() : null;}
size() {return this.items.length;}
}
const q = new WorkQueue(["a", "b"]);
const out = [q.pop()]; q.push("c"); out.push(q.pop());
console.log(out.join(",") + "|" + q.size());Try it yourself
<?php
declare(strict_types=1);
require_once __DIR__."/WorkQueue.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function queueReport(array $i):string{$q=new WorkQueue($i[0]);$out=[];foreach($i[1] as $op){if($op[0]==="push")$q->push($op[1]);else $out[]=$q->pop()??"EMPTY";}return implode(",",$out)."|".$q->size();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new WorkQueue(["a"]);$b=new WorkQueue([]);ensure($a->pop()==="a" && $a->pop()===null && $b->size()===0,"queue independence");$a->push("z");ensure($a->size()===1 && $a->pop()==="z","queue API");
echo queueReport($input),"\n";
All lessons in PHP for JavaScript Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batchPractice on your own: Online PHP compiler