Skip to content

Instantly share code, notes, and snippets.

@not-an-aardvark
Last active March 7, 2018 04:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save not-an-aardvark/2f9b6d198de70892db02e171be6184c3 to your computer and use it in GitHub Desktop.
Save not-an-aardvark/2f9b6d198de70892db02e171be6184c3 to your computer and use it in GitHub Desktop.
A function that only exists when accessed from strict mode
Object.defineProperty(
Array.prototype,
'flatten',
{
configurable: true,
set(value) {
Object.define(Array.prototype, 'flatten', { configurable: true, writable: true, value });
return value;
},
get: function returnUndefinedIfCallerIsSloppy(){
try {
returnUndefinedIfCallerIsSloppy.caller.caller;
return undefined;
} catch (e) {
return function flatten() { /* flatten the array */ };
}
}
}
);
[].flatten; // -> ƒ flatten() { /* flatten the array */ }
(function(){ return [].flatten })(); // -> undefined
(function(){ 'use strict'; return [].flatten })(); // -> ƒ flatten() { /* flatten the array */ }
@coreh
Copy link

coreh commented Mar 7, 2018

This is so incredibly clever 😲

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment