1// Copyright 2016 the V8 project authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5(function(global, utils) { 6 7%CheckIsBootstrapping(); 8 9// ------------------------------------------------------------------- 10// Imports 11 12var GlobalString = global.String; 13 14// ------------------------------------------------------------------- 15// http://tc39.github.io/proposal-string-pad-start-end/ 16 17function StringPad(thisString, maxLength, fillString) { 18 maxLength = TO_LENGTH(maxLength); 19 var stringLength = thisString.length; 20 21 if (maxLength <= stringLength) return ""; 22 23 if (IS_UNDEFINED(fillString)) { 24 fillString = " "; 25 } else { 26 fillString = TO_STRING(fillString); 27 if (fillString === "") { 28 // If filler is the empty String, return S. 29 return ""; 30 } 31 } 32 33 var fillLength = maxLength - stringLength; 34 var repetitions = (fillLength / fillString.length) | 0; 35 var remainingChars = (fillLength - fillString.length * repetitions) | 0; 36 37 var filler = ""; 38 while (true) { 39 if (repetitions & 1) filler += fillString; 40 repetitions >>= 1; 41 if (repetitions === 0) break; 42 fillString += fillString; 43 } 44 45 if (remainingChars) { 46 filler += %_SubString(fillString, 0, remainingChars); 47 } 48 49 return filler; 50} 51 52function StringPadStart(maxLength, fillString) { 53 CHECK_OBJECT_COERCIBLE(this, "String.prototype.padStart") 54 var thisString = TO_STRING(this); 55 56 return StringPad(thisString, maxLength, fillString) + thisString; 57} 58%FunctionSetLength(StringPadStart, 1); 59 60function StringPadEnd(maxLength, fillString) { 61 CHECK_OBJECT_COERCIBLE(this, "String.prototype.padEnd") 62 var thisString = TO_STRING(this); 63 64 return thisString + StringPad(thisString, maxLength, fillString); 65} 66%FunctionSetLength(StringPadEnd, 1); 67 68utils.InstallFunctions(GlobalString.prototype, DONT_ENUM, [ 69 "padStart", StringPadStart, 70 "padEnd", StringPadEnd 71]); 72 73}); 74