Last active
November 6, 2019 11:46
-
-
Save bkeating/411db72308aa538be189e56a51150810 to your computer and use it in GitHub Desktop.
My personal, ongoing list of useful JavaScript prototype polyfills ¯\_(ツ)_/¯
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* String.capitalize - Capitalize the first character of a string. | |
* | |
* Example: | |
* const foo = "this is a headline" | |
* foo.capitalize() | |
* This is a headline | |
*/ | |
String.prototype.capitalize = function() { | |
return this.charAt(0).toUpperCase() + this.slice(1); | |
}; | |
/** | |
* Array.chunk() - Break an array down into chunks | |
* | |
* Example: | |
* const foo = [1,2,3,4,5,6,7,8,9,10] | |
* foo.chunk(3) | |
* [[1,2,3], [4,5,6], [7,8,9], [10] | |
*/ | |
Object.defineProperty(Array.prototype, 'chunk', { | |
value: function(n) { | |
return Array.from(Array(Math.ceil(this.length / n)), (_, i) => | |
this.slice(i * n, i * n + n) | |
); | |
} | |
}); | |
/** | |
* Date.getWeekNumber() - returns int of current week of the year | |
*/ | |
Date.prototype.getWeekNumber = function() { | |
var d = new Date( | |
Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()) | |
); | |
var dayNum = d.getUTCDay() || 7; | |
d.setUTCDate(d.getUTCDate() + 4 - dayNum); | |
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); | |
return Math.ceil(((d - yearStart) / 86400000 + 1) / 7); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment