NASHORN-208.js revision 6:5a1b0714df0e
152419Sjulian/* 252419Sjulian * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 352419Sjulian * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4139823Simp * 5139823Simp * This code is free software; you can redistribute it and/or modify it 6139823Simp * under the terms of the GNU General Public License version 2 only, as 752419Sjulian * published by the Free Software Foundation. 852419Sjulian * 952419Sjulian * This code is distributed in the hope that it will be useful, but WITHOUT 1052419Sjulian * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1152419Sjulian * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 1252419Sjulian * version 2 for more details (a copy is included in the LICENSE file that 1352419Sjulian * accompanied this code). 1452419Sjulian * 1552419Sjulian * You should have received a copy of the GNU General Public License version 1652419Sjulian * 2 along with this work; if not, write to the Free Software Foundation, 1752419Sjulian * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 1852419Sjulian * 1952419Sjulian * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2052419Sjulian * or visit www.oracle.com if you need additional information or have any 2152419Sjulian * questions. 2252419Sjulian */ 2352419Sjulian 2452419Sjulian/** 2552419Sjulian * NASHORN-208 2652419Sjulian * 2752419Sjulian * @test 2852419Sjulian * @run 2952419Sjulian */ 3052419Sjulian 3152419Sjulianvar inspect = function(x) { return x; } 3252419Sjulian 3352419Sjulianvar formatRegExp = /%[sdj%]/g; 3452419Sjulian 3552419Sjulianvar format = function(f) { 3652419Sjulian if (typeof f !== 'string') { 3752419Sjulian var objects = []; 3852419Sjulian for (var i = 0; i < arguments.length; i++) { 3967506Sjulian objects.push(inspect(arguments[i])); 4052419Sjulian } 4152419Sjulian return objects.join(' '); 4252419Sjulian } 4352419Sjulian 4452419Sjulian var i = 1; 45122481Sru var args = arguments; 46122481Sru var len = args.length; 4752419Sjulian var str = String(f).replace(formatRegExp, function(x) { 4852419Sjulian if (i >= len) return x; 4952419Sjulian switch (x) { 5052419Sjulian case '%s': return String(args[i++]); 5152419Sjulian case '%d': return Number(args[i++]); 5252419Sjulian case '%j': return JSON.stringify(args[i++]); 5352419Sjulian case '%%': return '%'; 5452419Sjulian default: 5552419Sjulian return x; 5652419Sjulian } 5752419Sjulian }); 5852817Sarchie for (var x = args[i]; i < len; x = args[++i]) { 5952817Sarchie if (x === null || typeof x !== 'object') { 6052817Sarchie str += ' ' + x; 6152817Sarchie } else { 6252817Sarchie str += ' ' + inspect(x); 6352817Sarchie } 6452817Sarchie } 6552817Sarchie return str; 6656658Sarchie}; 6756658Sarchie 6864507Sarchievar s = format('%s %s', 'foo', 'bar', 'hop'); 6964507Sarchieprint(s); 7064507Sarchie 7164507Sarchie