The Polyfill filter adds JavaScript prototype polyfills for Ruby methods that don’t have direct JavaScript equivalents. Unlike the Functions filter which transforms method calls inline (e.g., .first becomes [0]), the Polyfill filter preserves the Ruby method names and adds runtime polyfill definitions at the top of your output.
This is useful when you want to:
Keep Ruby-style method names in your JavaScript for readability
Use methods like first and last as property accessors (without parentheses)
Supported Methods
Array Methods
Ruby
JavaScript Polyfill
.first
Property getter returning this[0]
.last
Property getter returning this.at(-1)
.compact
Property getter returning new array without null/undefined
The $Hash class provides Ruby’s Hash.new behavior where accessing missing keys returns a default value or calls a block. This is useful for auto-vivifying hashes:
# Counter with default 0counts=Hash.new(0)counts[:a]+=1# Nested hash auto-vivificationnested=Hash.new{|h,k|h[k]=[]}nested[:users]<<"Alice"
// Output (polyfills prepended, then code)Object.defineProperty(Array.prototype,"first",{get(){returnthis[0]},configurable:true});Object.defineProperty(Array.prototype,"last",{get(){returnthis.at(-1)},configurable:true});Object.defineProperty(Array.prototype,"compact",{get(){returnthis.filter(x=>x!==null&&x!==undefined)},configurable:true});Object.defineProperty(Array.prototype,"uniq",{get(){return[...newSet(this)]},configurable:true});if (!String.prototype.chomp){String.prototype.chomp=function(suffix){if (suffix===undefined)returnthis.replace(/\r?\n$/m,"");if (this.endsWith(suffix))returnthis.slice(0,this.length-suffix.length);returnString(this)}}Object.defineProperty(Object.prototype,"to_a",{get(){returnObject.entries(this)},configurable:true});arr.first;arr.last;arr.compact;arr.uniq;str.chomp("\n");hash.to_a
Polyfill vs Functions Filter
The key difference between Polyfill and Functions:
Method
Polyfill Filter
Functions Filter
arr.first
arr.first (property)
arr[0]
arr.last
arr.last (property)
arr[arr.length - 1]
arr.compact
arr.compact (property)
arr.filter(x => x != null)
arr.uniq
arr.uniq (property)
[...new Set(arr)]
str.chomp
str.chomp() (method)
str.replace(/\\r?\\n$/, "")
Choose Polyfill when you want Ruby-style method names preserved in the output. Choose Functions when you want zero-runtime-overhead inline transformations.