Skip to content

Instantly share code, notes, and snippets.

@azproduction
Forked from 140bytes/LICENSE.txt
Created September 13, 2012 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save azproduction/3713970 to your computer and use it in GitHub Desktop.
Save azproduction/3713970 to your computer and use it in GitHub Desktop.
Ugly forEach polyfill for primitives

Ugly forEach polyfill for primitives

  • no index argument
  • no objects in array
  • no strings in array with ","
function (array, iterator) {
// array = [1,2,3,4,,"pewpew"];
// array.toString() -> "1,2,3,4,,pewpew"
// string.replace(/[^,]+/g, iterator);
// itreator(item);
''.replace.call(array, /[^,]+/g, iterator);
}
function(a, i){''.replace.call(a,/[^,]+/g,i)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "Ugly forEach",
"description": "Ugly forEach polyfill for primitives",
"keywords": [
"polyfill"
]
}
<!DOCTYPE html>
<title>Ugly forEach</title>
<div>Expected value: <b>246NaN</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var myFunction = function(){
var result = "";
return (function(a, i){''.replace.call(a,/[^,]+/g,i)})
([1,2,3,,,"pewpew"], function (item) {
result += item * 2;
}), result; // "246NaN"
}
document.getElementById( "ret" ).innerHTML = myFunction();
</script>
@azproduction
Copy link
Author

With extra return and split(',') it can be transformed to ugly map() :-)

@jed
Copy link

jed commented Sep 13, 2012

ha, clever!

@3rd-Eden
Copy link

@azproduction The mapping would not work as everything will be cast to a string.

@twolfson
Copy link

Removed 4 bytes, down to 41 bytes. https://gist.github.com/3714916

@tsaniel
Copy link

tsaniel commented Sep 14, 2012

Actually this method is not only ugly but rough as well.
For example, a string element containing a comma will break the "string array".
It doesn't work with object element too.

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