/** * Demonstrates the ADD opcode working with arrays * * ADD now handles array concatenation: * - [1, 2, 3] + [4] === [1, 2, 3, 4] * - If both operands are arrays, they are concatenated */ import { toBytecode, run } from "#reef" // Basic array concatenation const basicConcat = toBytecode([ ["PUSH", 1], ["PUSH", 2], ["PUSH", 3], ["MAKE_ARRAY", 3], ["PUSH", 4], ["MAKE_ARRAY", 1], ["ADD"], ["HALT"] ]) console.log('Basic array concatenation ([1, 2, 3] + [4]):') const result1 = await run(basicConcat) console.log(result1) // Output: { type: 'array', value: [1, 2, 3, 4] } // Concatenate two multi-element arrays const multiConcat = toBytecode([ ["PUSH", 1], ["PUSH", 2], ["MAKE_ARRAY", 2], ["PUSH", 3], ["PUSH", 4], ["MAKE_ARRAY", 2], ["ADD"], ["HALT"] ]) console.log('\nConcatenate two arrays ([1, 2] + [3, 4]):') const result2 = await run(multiConcat) console.log(result2) // Output: { type: 'array', value: [1, 2, 3, 4] } // Concatenate multiple arrays in sequence const multipleConcat = toBytecode([ ["PUSH", 1], ["MAKE_ARRAY", 1], ["PUSH", 2], ["MAKE_ARRAY", 1], ["ADD"], ["PUSH", 3], ["MAKE_ARRAY", 1], ["ADD"], ["PUSH", 4], ["MAKE_ARRAY", 1], ["ADD"], ["HALT"] ]) console.log('\nMultiple concatenations ([1] + [2] + [3] + [4]):') const result3 = await run(multipleConcat) console.log(result3) // Output: { type: 'array', value: [1, 2, 3, 4] } // Concatenate arrays with mixed types const mixedTypes = toBytecode([ ["PUSH", 1], ["PUSH", "hello"], ["MAKE_ARRAY", 2], ["PUSH", true], ["PUSH", null], ["MAKE_ARRAY", 2], ["ADD"], ["HALT"] ]) console.log('\nConcatenate arrays with mixed types ([1, "hello"] + [true, null]):') const result4 = await run(mixedTypes) console.log(result4) // Output: { type: 'array', value: [1, "hello", true, null] } // Concatenate empty array with non-empty const emptyConcat = toBytecode([ ["MAKE_ARRAY", 0], ["PUSH", 1], ["PUSH", 2], ["PUSH", 3], ["MAKE_ARRAY", 3], ["ADD"], ["HALT"] ]) console.log('\nConcatenate empty array with [1, 2, 3] ([] + [1, 2, 3]):') const result5 = await run(emptyConcat) console.log(result5) // Output: { type: 'array', value: [1, 2, 3] } // Nested arrays const nestedConcat = toBytecode([ ["PUSH", 1], ["PUSH", 2], ["MAKE_ARRAY", 2], ["MAKE_ARRAY", 1], ["PUSH", 3], ["PUSH", 4], ["MAKE_ARRAY", 2], ["MAKE_ARRAY", 1], ["ADD"], ["HALT"] ]) console.log('\nConcatenate nested arrays ([[1, 2]] + [[3, 4]]):') const result6 = await run(nestedConcat) console.log(result6) // Output: { type: 'array', value: [[1, 2], [3, 4]] }