Special method ‣ valueOf() - chung-leong/zigar GitHub Wiki

This method creates a "JavaScript version" of a Zig data object. Structs become regular JavaScript objects. Arrays and vectors become regular JavaScript arrays. Enums become strings. Pointers become the valueOf() of their targets.

This function is able to handle recursive references. Example:

const std = @import("std");

const NodeType = enum { red, blue };
pub const Node = struct {
    type: NodeType,
    id: i64,
    parent: ?*const @This() = null,
    children: ?[]*const @This() = null,
};

pub fn getRoot(allocator: std.mem.Allocator) !*const Node {
    const root: *Node = try allocator.create(Node);
    root.* = .{ .type = .red, .id = 0 };
    const child1: *Node = try allocator.create(Node);
    child1.* = .{ .type = .blue, .id = 1, .parent = root };
    const child2: *Node = try allocator.create(Node);
    child2.* = .{ .type = .blue, .id = 2, .parent = root };
    const children = try allocator.alloc(*const Node, 2);
    children[0] = child1;
    children[1] = child2;
    root.children = children;
    return root;
}
import { getRoot } from './valueof-example-1.zig';

const root = getRoot();
console.log(root.valueOf());
<ref *1> {
  type: 'red',
  id: 0n,
  parent: null,
  children: [
    { type: 'blue', id: 1n, parent: [Circular *1], children: null },
    { type: 'blue', id: 2n, parent: [Circular *1], children: null }
  ]
}

This method is useful when you need to dump an object into the development console.


Special methods

⚠️ **GitHub.com Fallback** ⚠️