TypeScript's type system, 206 bytes
//@ts-ignore
type F<C,S=[0,0]>=[S,C]extends[[infer A,infer B,...infer V],[infer I,...infer R]]?F<R,I extends`${any}`?[I,...S]:[...[[B],[A,A,B],[B,A],[`${A}${B}`],B extends`${A}${infer Z}`?[Z]:0][I],...V]>:S
Try it at the TS playground
This is a generic type F<C>
which takes input as a tuple of items which are either unary numbers as strings of 1s, or numbers 0 to 4 for the 5 commands:
num |
function |
0 |
Pop |
1 |
Duplicate |
2 |
Swap |
3 |
Add |
4 |
Subtract |
This solution works identically to the one below, only it skips the step of splitting on spaces, and indexes into an array instead of a dictionary, so it ends up quite a bit shorter.
TypeScript’s type system, 324 309 251 220 bytes
This is a generic type F<S>F<C>
which takes input as a string type of space separated commands or unary numbers, space terminated. Output in unary, first element is top of stack.