Pulse
pulse.js

Builtins

JavaScript built-in classes for transpiled Python code

Builtins

JavaScript built-in classes wrapped for use in @ps.javascript decorated functions. These classes transpile to their JavaScript equivalents with new constructors and static methods.

from pulse.js import (
    AbortController,
    AbortSignal,
    Animation,
    Array,
    ArrayBuffer,
    BigInt64Array,
    BigUint64Array,
    Blob,
    CustomEvent,
    DataView,
    Date,
    DOMParser,
    DocumentTimeline,
    Error,
    File,
    FileReader,
    Float32Array,
    Float64Array,
    FormData,
    Headers,
    Int16Array,
    Int32Array,
    Int8Array,
    IntersectionObserver,
    KeyframeEffect,
    Map,
    MutationObserver,
    Number,
    Object,
    PerformanceObserver,
    Promise,
    RegExp,
    Request,
    ResizeObserver,
    Response,
    Set,
    String,
    TextDecoder,
    TextEncoder,
    Uint16Array,
    Uint32Array,
    Uint8Array,
    Uint8ClampedArray,
    URL,
    URLSearchParams,
    WeakMap,
    WeakSet,
    XMLSerializer,
)

Array

JavaScript Array - a generic indexed collection.

from pulse.js import Array

@ps.javascript
def example():
    arr = Array(10)              # -> new Array(10)
    arr = Array(1, 2, 3)         # -> new Array(1, 2, 3)

Static methods

MethodDescription
Array.isArray(value)Check if value is an array
Array.from_(iterable)Create array from iterable (note the underscore)
Array.from_(iterable, mapFn)Create array with mapping function
Array.of(*elements)Create array from arguments

Properties

PropertyDescription
lengthNumber of elements

Mutator methods

These modify the array in place:

MethodDescription
push(*items)Add items to end, return new length
pop()Remove and return last item
shift()Remove and return first item
unshift(*items)Add items to start, return new length
splice(start, deleteCount, *items)Remove/replace elements
reverse()Reverse in place
sort(compareFn=None)Sort in place
fill(value, start=0, end=None)Fill with value
copyWithin(target, start=0, end=None)Copy within array

Accessor methods

These return new arrays or values:

MethodDescription
concat(*items)Merge arrays/values
slice(start=0, end=None)Return portion
join(separator=",")Join to string
indexOf(element, fromIndex=0)First index of element
lastIndexOf(element, fromIndex=None)Last index of element
includes(element, fromIndex=0)Check if contains
at(index)Get at index (supports negative)
flat(depth=1)Flatten nested arrays
flatMap(callback)Map then flatten by one level
toReversed()Return new reversed array (ES2023)
toSorted(compareFn=None)Return new sorted array (ES2023)
toSpliced(start, deleteCount, *items)Return new spliced array (ES2023)
with_(index, value)Return new array with element replaced (ES2023)

Iteration methods

MethodDescription
forEach(callback)Execute for each element
map(callback)Create array with mapped values
filter(callback)Create array with passing elements
reduce(callback, initialValue=None)Reduce to single value (left to right)
reduceRight(callback, initialValue=None)Reduce right to left
find(callback)First element passing test
findIndex(callback)Index of first passing element
findLast(callback)Last element passing test (ES2023)
findLastIndex(callback)Index of last passing element (ES2023)
every(callback)Test if all pass
some(callback)Test if any pass
keys()Iterator of indices
values()Iterator of values
entries()Iterator of [index, value] pairs

Example

from pulse.js import Array

@ps.javascript
def process_items(items):
    # Filter and map
    result = Array.from_(items).filter(
        lambda x, i, arr: x > 0
    ).map(
        lambda x, i, arr: x * 2
    )

    # Reduce
    total = result.reduce(lambda acc, x, i, arr: acc + x, 0)

    return total

Date

JavaScript Date - date and time handling.

from pulse.js import Date

@ps.javascript
def example():
    now = Date()                      # -> new Date()
    specific = Date("2024-01-15")     # -> new Date("2024-01-15")
    timestamp = Date.now()            # -> Date.now()

Static methods

MethodDescription
Date.now()Current timestamp in milliseconds
Date.parse(dateString)Parse date string to timestamp
Date.UTC(year, month, ...)Create UTC timestamp

Instance methods (getters)

MethodDescription
getDate()Day of month (1-31)
getDay()Day of week (0-6)
getFullYear()Four-digit year
getHours()Hours (0-23)
getMilliseconds()Milliseconds (0-999)
getMinutes()Minutes (0-59)
getMonth()Month (0-11)
getSeconds()Seconds (0-59)
getTime()Timestamp in milliseconds
getTimezoneOffset()UTC offset in minutes

UTC variants: getUTCDate(), getUTCDay(), getUTCFullYear(), etc.

Instance methods (setters)

MethodDescription
setDate(date)Set day of month
setFullYear(year, month?, date?)Set year
setHours(hours, min?, sec?, ms?)Set hours
setMilliseconds(ms)Set milliseconds
setMinutes(min, sec?, ms?)Set minutes
setMonth(month, date?)Set month
setSeconds(sec, ms?)Set seconds
setTime(time)Set timestamp

UTC variants: setUTCDate(), setUTCFullYear(), etc.

String methods

MethodDescription
toDateString()Date portion as string
toISOString()ISO 8601 format
toJSON()JSON representation
toLocaleDateString(locales?, options?)Locale date string
toLocaleString(locales?, options?)Locale date/time string
toLocaleTimeString(locales?, options?)Locale time string
toString()Full string representation
toTimeString()Time portion as string
toUTCString()UTC string
valueOf()Primitive value (timestamp)

Error

JavaScript Error types for error handling.

from pulse.js import Error, throw
from pulse.js.error import TypeError, RangeError, ReferenceError

@ps.javascript
def example():
    throw(Error("Something went wrong"))
    throw(TypeError("Expected a string"))

Error class

Property/MethodDescription
messageError message
nameError type name
stackStack trace (if available)
toString()String representation

Error types

All error types have the same interface as Error:

  • Error - Base error
  • TypeError - Type mismatch
  • RangeError - Value out of range
  • ReferenceError - Invalid reference
  • SyntaxError - Syntax error
  • EvalError - Eval error
  • URIError - URI handling error

Using throw

The throw function converts to a JavaScript throw statement:

from pulse.js import Error, throw

@ps.javascript
def validate(value):
    if value < 0:
        throw(RangeError("Value must be non-negative"))
    return value

Map

JavaScript Map - a key-value collection that preserves insertion order.

from pulse.js import Map

@ps.javascript
def example():
    m = Map()                         # -> new Map()
    m = Map([["a", 1], ["b", 2]])     # -> new Map([["a", 1], ["b", 2]])

Properties

PropertyDescription
sizeNumber of entries

Methods

MethodDescription
clear()Remove all entries
delete(key)Remove entry, return True if existed
get(key)Get value for key
has(key)Check if key exists
set(key, value)Set entry, return Map for chaining
forEach(callback)Execute for each entry
keys()Iterator of keys
values()Iterator of values
entries()Iterator of [key, value] pairs

Example

from pulse.js import Map

@ps.javascript
def build_lookup(items):
    lookup = Map()
    for item in items:
        lookup.set(item.id, item)

    if lookup.has("abc"):
        return lookup.get("abc")
    return None

Number

JavaScript Number - numeric utilities.

from pulse.js import Number

@ps.javascript
def example():
    Number.isFinite(42)           # -> Number.isFinite(42)
    Number.MAX_SAFE_INTEGER       # -> Number.MAX_SAFE_INTEGER

Constants

ConstantDescription
EPSILONSmallest difference between numbers
MAX_SAFE_INTEGERMaximum safe integer (2^53 - 1)
MIN_SAFE_INTEGERMinimum safe integer
MAX_VALUEMaximum representable number
MIN_VALUEMinimum positive number
NaNNot-a-Number
NEGATIVE_INFINITYNegative infinity
POSITIVE_INFINITYPositive infinity

Static methods

MethodDescription
isFinite(value)Check if finite number
isInteger(value)Check if integer
isNaN(value)Check if NaN
isSafeInteger(value)Check if safe integer
parseFloat(string)Parse float from string
parseInt(string, radix=10)Parse integer from string

Object

JavaScript Object utilities - static methods for object manipulation.

from pulse.js import Object

@ps.javascript
def example():
    keys = Object.keys(data)          # -> Object.keys(data)
    merged = Object.assign({}, a, b)  # -> Object.assign({}, a, b)

Static methods

MethodDescription
assign(target, *sources)Copy properties to target
create(proto, properties?)Create with prototype
defineProperty(obj, prop, descriptor)Define property
defineProperties(obj, props)Define multiple properties
entries(obj)Array of [key, value] pairs
freeze(obj)Prevent modifications
fromEntries(entries)Create from [key, value] pairs
getOwnPropertyDescriptor(obj, prop)Get property descriptor
getOwnPropertyDescriptors(obj)Get all descriptors
getOwnPropertyNames(obj)All own property names
getOwnPropertySymbols(obj)All own Symbol properties
getPrototypeOf(obj)Get prototype
hasOwn(obj, prop)Check own property
is_(value1, value2)SameValue comparison (note underscore)
isExtensible(obj)Check if extensible
isFrozen(obj)Check if frozen
isSealed(obj)Check if sealed
keys(obj)Array of enumerable keys
preventExtensions(obj)Prevent adding properties
seal(obj)Prevent adding/removing properties
setPrototypeOf(obj, prototype)Set prototype
values(obj)Array of enumerable values
groupBy(items, keyFn)Group items by key (ES2024)

Promise

JavaScript Promise - async operation handling.

from pulse.js import Promise

@ps.javascript
async def example():
    result = await Promise.resolve(42)
    data = await fetch("/api/data")

Constructor

Promise(lambda resolve, reject: ...)

Static methods

MethodDescription
resolve(value?)Create resolved promise
reject(reason)Create rejected promise
all(iterable)Wait for all to resolve
allSettled(iterable)Wait for all to settle
any(iterable)First to fulfill
race(iterable)First to settle
withResolvers()Create with exposed resolve/reject (ES2024)

Instance methods

MethodDescription
then(onFulfilled?, onRejected?)Attach handlers
catch(onRejected)Attach rejection handler
finally_(onFinally)Attach settlement handler (note underscore)

Async/await

Promise supports Python's await syntax:

@ps.javascript
async def fetch_data():
    response = await fetch("/api/data")
    data = await response.json()
    return data

URL

URL parser and serializer.

from pulse.js import URL

@ps.javascript
def example():
    url = URL("https://example.com?foo=1#section")
    return url.href, url.searchParams.toString()

Properties

PropertyDescription
hrefFull URL string
originScheme + host + port
protocolScheme (e.g. "https:")
usernameUsername
passwordPassword
hostHost + port
hostnameHost without port
portPort
pathnamePath
searchQuery string with leading ?
hashFragment with leading #
searchParamsURLSearchParams instance

Methods

MethodDescription
toString()Serialize to string (same as href)
toJSON()JSON serialization

URLSearchParams

Query string utility.

from pulse.js import URLSearchParams

@ps.javascript
def example():
    params = URLSearchParams("foo=1&bar=2")
    params.append("bar", "3")
    return params.toString()

Properties

PropertyDescription
sizeTotal number of params

Methods

MethodDescription
append(name, value)Add a parameter
delete(name, value=None)Remove parameter(s)
get(name)First value
getAll(name)All values
has(name, value=None)Check for param
set(name, value)Set and replace
sort()Sort by key
toString()Serialize
entries()Iterator of pairs
keys()Iterator of keys
values()Iterator of values

AbortController

Abort async operations via signals.

from pulse.js import AbortController

@ps.javascript
def example():
    controller = AbortController()
    controller.abort()
    return controller.signal.aborted

Properties

PropertyDescription
signalAbortSignal instance

Methods

MethodDescription
abort()Trigger abort

AbortSignal

Property/MethodDescription
abortedTrue if aborted
onabortEvent handler
throwIfAborted()Throw if aborted

Fetch API

Headers, Request, Response, and fetch().

from pulse.js import Headers, Request, fetch, obj

@ps.javascript
def example():
    headers = Headers()
    headers.set("Content-Type", "application/json")
    req = Request("/api", obj(method="POST", headers=headers, body="{}"))
    return fetch(req)

Headers methods

MethodDescription
append(name, value)Add header value
delete(name)Remove header
get(name)Get first value
has(name)Check header
set(name, value)Set header
forEach(cb, thisArg=None)Iterate

Request properties

PropertyDescription
urlRequest URL
methodHTTP method
headersHeaders
bodyRequest body

Response properties/methods

Property/MethodDescription
okStatus 2xx
statusStatus code
headersHeaders
bodyBody stream
json()Parse JSON
text()Read text
blob()Read Blob
formData()Read FormData
arrayBuffer()Read ArrayBuffer

FormData

Form-like key/value collection for multipart requests.

from pulse.js import FormData

@ps.javascript
def example():
    data = FormData()
    data.append("name", "Ada")
    return data.get("name")

Methods

MethodDescription
append(name, value, filename=None)Append value
set(name, value, filename=None)Set value
delete(name)Remove key
get(name)First value
getAll(name)All values
has(name)Check key
entries()Iterator of pairs
keys()Iterator of keys
values()Iterator of values
forEach(cb, thisArg=None)Iterate

Blob

Binary data container.

from pulse.js import Blob, obj

@ps.javascript
def example():
    blob = Blob(["hello"], obj(type="text/plain"))
    return blob.size

Properties

PropertyDescription
sizeSize in bytes
typeMIME type

Methods

MethodDescription
arrayBuffer()Read as ArrayBuffer
bytes()Read as Uint8Array
slice(start=None, end=None, contentType=None)Slice
stream()ReadableStream
text()Read as text

File

Blob with name/metadata.

from pulse.js import File, obj

@ps.javascript
def example():
    f = File(["hello"], "note.txt", obj(type="text/plain"))
    return f.name

Properties

PropertyDescription
nameFile name
lastModifiedLast modified timestamp
webkitRelativePathRelative path (if any)

FileReader

Reads File/Blob contents.

from pulse.js import FileReader

@ps.javascript
def example(blob):
    reader = FileReader()
    reader.readAsText(blob)
    return reader.result

Methods

MethodDescription
readAsText(blob, encoding=None)Read as text
readAsArrayBuffer(blob)Read as ArrayBuffer

TextEncoder / TextDecoder

UTF-8 encode/decode helpers.

from pulse.js import TextEncoder, TextDecoder

@ps.javascript
def example(text: str):
    enc = TextEncoder()
    data = enc.encode(text)
    dec = TextDecoder("utf-8")
    return dec.decode(data)

TextEncoder

Property/MethodDescription
encodingAlways "utf-8"
encode(string="")Encode to Uint8Array
encodeInto(string, destination)Encode into buffer

TextDecoder

Property/MethodDescription
encodingDecoder encoding
fatalFatal mode
ignoreBOMIgnore BOM
decode(input=None, options=None)Decode bytes

ArrayBuffer / Typed Arrays

Binary buffers and views.

from pulse.js import ArrayBuffer, Uint8Array

@ps.javascript
def example():
    buf = ArrayBuffer(8)
    view = Uint8Array(buf)
    return buf.byteLength, view.byteLength

ArrayBuffer

Property/MethodDescription
byteLengthSize in bytes
slice(begin=0, end=None)Copy range
isView(value)Check view

DataView

PropertyDescription
bufferBacking buffer
byteLengthView length
byteOffsetView offset

Typed array classes

Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array.


IntersectionObserver

Observe element visibility changes.

from pulse.js import IntersectionObserver, obj

@ps.javascript
def example(target):
    observer = IntersectionObserver(lambda entries, obs: None, obj(threshold=0.5))
    observer.observe(target)

Methods

MethodDescription
observe(target)Start observing
unobserve(target)Stop observing target
disconnect()Stop all observations
takeRecords()Pending entries

ResizeObserver

Observe element size changes.

from pulse.js import ResizeObserver, obj

@ps.javascript
def example(target):
    observer = ResizeObserver(lambda entries, obs: None)
    observer.observe(target, obj(box="border-box"))

Methods

MethodDescription
observe(target, options=None)Start observing
unobserve(target)Stop observing target
disconnect()Stop all observations

PerformanceObserver

Observe performance entry events.

from pulse.js import PerformanceObserver, obj

@ps.javascript
def example():
    observer = PerformanceObserver(lambda list_, obs: None)
    observer.observe(obj(entryTypes=["mark", "measure"]))

Methods

MethodDescription
observe(options)Start observing
disconnect()Stop observing
takeRecords()Pending entries

Web animations

The Web Animations API lets you create smooth, performant animations from Python code. Unlike CSS animations, you get programmatic control—pause, reverse, seek to any point, or chain animations with promises.

from pulse.js import Animation, KeyframeEffect, document, obj

@ps.javascript
def fade_in(element):
    # Define what animates: target element, keyframes, and timing
    effect = KeyframeEffect(
        element,
        [obj(opacity=0), obj(opacity=1)],  # From invisible to visible
        obj(duration=300, easing="ease-out", fill="forwards"),
    )

    # Create and start the animation
    animation = Animation(effect, document.timeline)
    animation.play()
    return animation

When to use Web Animations

Use it when you need to:

  • Control animations from code (pause, reverse, speed up)
  • Wait for an animation to finish before doing something else
  • Animate based on runtime values (user input, scroll position)
  • Coordinate multiple animations

For simple hover effects or static transitions, CSS is usually simpler.

KeyframeEffect

Defines what gets animated. Pass a target element, keyframes, and timing options.

effect = KeyframeEffect(
    target,                                    # Element to animate
    [obj(opacity=0), obj(opacity=1)],          # Keyframes (array of states)
    obj(duration=300, easing="ease-in-out"),   # Timing options
)

Keyframes are an array of style states. The animation interpolates between them:

# Slide and fade in
[
    obj(opacity=0, transform="translateY(-20px)"),
    obj(opacity=1, transform="translateY(0)"),
]

# Bounce effect (multiple keyframes)
[
    obj(transform="scale(1)"),
    obj(transform="scale(1.2)"),
    obj(transform="scale(1)"),
]

Timing options control how the animation plays:

OptionDescription
durationLength in milliseconds (e.g., 300)
easingTiming function: "linear", "ease", "ease-in", "ease-out", "ease-in-out", or a cubic-bezier
fillWhat happens when animation ends: "none", "forwards" (keep end state), "backwards", "both"
iterationsHow many times to repeat (use Infinity for forever)
direction"normal", "reverse", "alternate", "alternate-reverse"
delayWait before starting (milliseconds)
endDelayWait after ending (milliseconds)
iterationStartOffset into the iteration to start at (0-1)

KeyframeEffect properties

PropertyDescription
targetThe element being animated
compositeHow values combine with underlying styles
iterationCompositeHow values accumulate across iterations
pseudoElementTarget pseudo-element (e.g., "::before")

KeyframeEffect methods

MethodDescription
getTiming()Get current timing options
getComputedTiming()Get computed values including progress
getKeyframes()Get the computed keyframes
setKeyframes(keyframes)Replace keyframes mid-animation
updateTiming(timing)Update timing options mid-animation

Animation

Controls playback of a KeyframeEffect. Think of it like a video player for your effect.

animation = Animation(effect, document.timeline)
animation.play()  # Start it

Animation properties

PropertyDescription
currentTimeCurrent position in milliseconds (read/write)
playState"idle", "running", "paused", "finished"
playbackRateSpeed multiplier (1 = normal, 2 = double speed, -1 = reverse)
finishedPromise that resolves when animation completes
readyPromise that resolves when animation is ready to play
pendingTrue if play/pause is pending
startTimeWhen animation started on the timeline
effectThe KeyframeEffect being played (read/write)
timelineThe timeline this animation is attached to (read/write)
idAnimation identifier string (read/write)
replaceState"active", "removed", or "persisted"
overallProgressProgress across all iterations (0-1)

Animation methods

MethodDescription
play()Start or resume playback
pause()Pause at current position
reverse()Play backwards from current position
finish()Jump to end (or start if reversed)
cancel()Stop and reset to initial state
commitStyles()Write current animated values to element's style
persist()Prevent automatic removal when finished
updatePlaybackRate(rate)Smoothly change speed without jumping

Waiting for animations

The finished promise lets you chain actions:

@ps.javascript
async def animate_then_remove(element):
    effect = KeyframeEffect(
        element,
        [obj(opacity=1), obj(opacity=0)],
        obj(duration=200, fill="forwards"),
    )
    animation = Animation(effect, document.timeline)
    animation.play()

    # Wait for fade out to complete
    await animation.finished

    # Now safe to remove
    element.remove()

DocumentTimeline

The default timeline tied to document.timeline. You rarely need to create one yourself, but you can for custom timing:

from pulse.js import DocumentTimeline

# Custom timeline with offset origin
timeline = DocumentTimeline(obj(originTime=1000))
animation = Animation(effect, timeline)
PropertyDescription
currentTimeCurrent time on this timeline (milliseconds since origin)

Learn more: Animation (MDN), KeyframeEffect (MDN)


DOMParser / XMLSerializer

Parse and serialize DOM.

from pulse.js import DOMParser, XMLSerializer

@ps.javascript
def example(source: str):
    parser = DOMParser()
    doc = parser.parseFromString(source, "text/html")
    serializer = XMLSerializer()
    return serializer.serializeToString(doc)

DOMParser

MethodDescription
parseFromString(string, mimeType)Parse DOM

XMLSerializer

MethodDescription
serializeToString(root)Serialize DOM

CustomEvent

Custom event with detail.

from pulse.js import CustomEvent, obj

@ps.javascript
def example():
    event = CustomEvent("ping", obj(detail=obj(ok=True)))
    return event.detail

Properties

PropertyDescription
detailCustom payload

MutationObserver

Observe DOM changes in the browser.

from pulse.js import MutationObserver, obj

@ps.javascript
def example(target):
    observer = MutationObserver(lambda records, obs: None)
    observer.observe(target, obj(childList=True, subtree=True))

Methods

MethodDescription
observe(target, options)Start observing DOM mutations
disconnect()Stop observing
takeRecords()Return pending mutation records

Options

OptionDescription
childListWatch for child node additions/removals
attributesWatch for attribute changes
characterDataWatch for text changes
subtreeInclude all descendants
attributeOldValueRecord previous attribute value
characterDataOldValueRecord previous text value
attributeFilterList of attribute names to watch

RegExp

JavaScript RegExp - regular expressions.

from pulse.js import RegExp

@ps.javascript
def example():
    pattern = RegExp(r"\d+", "g")     # -> new RegExp("\\d+", "g")
    if pattern.test("abc123"):
        matches = pattern.exec("abc123")

Methods

MethodDescription
exec(string)Execute search, return matches or None
test(string)Test if pattern matches
toString()String representation

Properties

PropertyDescription
sourcePattern string
flagsFlag string
globGlobal flag (g)
ignoreCaseCase-insensitive flag (i)
multilineMultiline flag (m)
dotAllDot-all flag (s)
unicodeUnicode flag (u)
stickySticky flag (y)
lastIndexNext search start index

Set

JavaScript Set - a collection of unique values.

from pulse.js import Set

@ps.javascript
def example():
    s = Set()                         # -> new Set()
    s = Set([1, 2, 3])                # -> new Set([1, 2, 3])

Properties

PropertyDescription
sizeNumber of values

Methods

MethodDescription
add(value)Add value, return Set for chaining
clear()Remove all values
delete(value)Remove value, return True if existed
has(value)Check if value exists
forEach(callback)Execute for each value
keys()Iterator of values (same as values)
values()Iterator of values
entries()Iterator of [value, value] pairs

ES2024 Set methods

MethodDescription
union(other)Values in either set
intersection(other)Values in both sets
difference(other)Values in this but not other
symmetricDifference(other)Values in either but not both
isSubsetOf(other)Check if subset
isSupersetOf(other)Check if superset
isDisjointFrom(other)Check if no overlap

String

JavaScript String constructor and static methods.

from pulse.js import String

@ps.javascript
def example():
    String.fromCharCode(65)           # -> String.fromCharCode(65) -> "A"
    String.fromCodePoint(0x1F600)     # -> String.fromCodePoint(0x1F600) -> emoji

Static methods

MethodDescription
fromCharCode(*codes)Create from char codes
fromCodePoint(*codePoints)Create from code points
raw(template, *substitutions)Raw template literal

WeakMap

JavaScript WeakMap - key-value collection with weak key references.

from pulse.js import WeakMap

@ps.javascript
def example():
    cache = WeakMap()
    cache.set(obj, "value")

Keys must be objects. Entries are garbage collected when keys are no longer referenced.

Methods

MethodDescription
delete(key)Remove entry, return True if existed
get(key)Get value for key
has(key)Check if key exists
set(key, value)Set entry, return WeakMap for chaining

WeakSet

JavaScript WeakSet - collection with weak value references.

from pulse.js import WeakSet

@ps.javascript
def example():
    seen = WeakSet()
    seen.add(obj)

Values must be objects. Entries are garbage collected when values are no longer referenced.

Methods

MethodDescription
add(value)Add value, return WeakSet for chaining
delete(value)Remove value, return True if existed
has(value)Check if value exists

Special exports

obj

Create plain JavaScript object literals (not Maps):

from pulse.js import obj

@ps.javascript
def example():
    style = obj(color="red", fontSize="14px")  # -> { color: "red", fontSize: "14px" }

    # With spread
    merged = obj(**base, newKey="value")       # -> { ...base, newKey: "value" }

Use obj() when you need a plain JS object, like for React props or style objects. Python dict() transpiles to new Map().

undefined

The JavaScript undefined value:

from pulse.js import undefined

@ps.javascript
def example():
    if value is undefined:
        return "missing"

throw

Throw JavaScript errors:

from pulse.js import throw, Error

@ps.javascript
def validate(x):
    if x < 0:
        throw(Error("Must be positive"))

See also

On this page

Builtins
Array
TOC connector
Static methods
Properties
Mutator methods
Accessor methods
Iteration methods
Example
TOC connector
Date
TOC connector
Static methods
Instance methods (getters)
Instance methods (setters)
String methods
TOC connector
Error
TOC connector
Error class
Error types
Using throw
TOC connector
Map
TOC connector
Properties
Methods
Example
TOC connector
Number
TOC connector
Constants
Static methods
TOC connector
Object
TOC connector
Static methods
TOC connector
Promise
TOC connector
Constructor
Static methods
Instance methods
Async/await
TOC connector
URL
TOC connector
Properties
Methods
TOC connector
URLSearchParams
TOC connector
Properties
Methods
TOC connector
AbortController
TOC connector
Properties
Methods
AbortSignal
TOC connector
Fetch API
TOC connector
Headers methods
Request properties
Response properties/methods
TOC connector
FormData
TOC connector
Methods
TOC connector
Blob
TOC connector
Properties
Methods
TOC connector
File
TOC connector
Properties
TOC connector
FileReader
TOC connector
Methods
TOC connector
TextEncoder / TextDecoder
TOC connector
TextEncoder
TextDecoder
TOC connector
ArrayBuffer / Typed Arrays
TOC connector
ArrayBuffer
DataView
Typed array classes
TOC connector
IntersectionObserver
TOC connector
Methods
TOC connector
ResizeObserver
TOC connector
Methods
TOC connector
PerformanceObserver
TOC connector
Methods
TOC connector
Web animations
TOC connector
When to use Web Animations
KeyframeEffect
KeyframeEffect properties
KeyframeEffect methods
Animation
Animation properties
Animation methods
Waiting for animations
DocumentTimeline
TOC connector
DOMParser / XMLSerializer
TOC connector
DOMParser
XMLSerializer
TOC connector
CustomEvent
TOC connector
Properties
TOC connector
MutationObserver
TOC connector
Methods
Options
TOC connector
RegExp
TOC connector
Methods
Properties
TOC connector
Set
TOC connector
Properties
Methods
ES2024 Set methods
TOC connector
String
TOC connector
Static methods
TOC connector
WeakMap
TOC connector
Methods
TOC connector
WeakSet
TOC connector
Methods
TOC connector
Special exports
TOC connector
obj
undefined
throw
TOC connector
See also