blob: a6c6c474de5503e269b451b3fe89b1173e973453 [file] [log] [blame]
Ben Murdochda12d292016-06-02 14:46:10 +01001// 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;
13var MakeTypeError;
14
15utils.Import(function(from) {
16 MakeTypeError = from.MakeTypeError;
17});
18
19// -------------------------------------------------------------------
20// http://tc39.github.io/proposal-string-pad-start-end/
21
22function StringPad(thisString, maxLength, fillString) {
23 maxLength = TO_LENGTH(maxLength);
24 var stringLength = thisString.length;
25
26 if (maxLength <= stringLength) return "";
27
28 if (IS_UNDEFINED(fillString)) {
29 fillString = " ";
30 } else {
31 fillString = TO_STRING(fillString);
32 if (fillString === "") {
33 fillString = " ";
34 }
35 }
36
37 var fillLength = maxLength - stringLength;
38 var repetitions = (fillLength / fillString.length) | 0;
39 var remainingChars = (fillLength - fillString.length * repetitions) | 0;
40
41 var filler = "";
42 while (true) {
43 if (repetitions & 1) filler += fillString;
44 repetitions >>= 1;
45 if (repetitions === 0) break;
46 fillString += fillString;
47 }
48
49 if (remainingChars) {
50 filler += %_SubString(fillString, 0, remainingChars);
51 }
52
53 return filler;
54}
55
56function StringPadStart(maxLength, fillString) {
57 CHECK_OBJECT_COERCIBLE(this, "String.prototype.padStart")
58 var thisString = TO_STRING(this);
59
60 return StringPad(thisString, maxLength, fillString) + thisString;
61}
62%FunctionSetLength(StringPadStart, 1);
63
64function StringPadEnd(maxLength, fillString) {
65 CHECK_OBJECT_COERCIBLE(this, "String.prototype.padEnd")
66 var thisString = TO_STRING(this);
67
68 return thisString + StringPad(thisString, maxLength, fillString);
69}
70%FunctionSetLength(StringPadEnd, 1);
71
72utils.InstallFunctions(GlobalString.prototype, DONT_ENUM, [
73 "padStart", StringPadStart,
74 "padEnd", StringPadEnd
75]);
76
77});