Skip to content

Instantly share code, notes, and snippets.

@StuPig
Created May 8, 2012 17:31
Show Gist options
  • Save StuPig/2637689 to your computer and use it in GitHub Desktop.
Save StuPig/2637689 to your computer and use it in GitHub Desktop.
use javascript to archive Array's reverse features
// 题目:
// 假设有字符串 'i am a programmer'
// 实现方法全部颠倒,转成 'remmargorp a ma i'
var str = 'i am a programmer';
// 函数式递归调用方法实现
function reverseStrByChar(str) {
if (!str || Object.prototype.toString.call(str).toLowerCase().indexOf('string') < 0) {
throw new Error('reverseStrByChar: Invalid argument ' + str);
}
if (str.length === 0 || str.length === 1) {
return str;
} else {
return reverseStrByChar(str.substring(1)) + str.substring(0, 1)
}
}
console.log(reverseStrByChar(str));
// 假设题目变为:
// 实现方法转成 'programmer a am i'
// 调用JS built-in 方法
function reverseByBuiltIn(str) {
if (!str || Object.prototype.toString.call(str).toLowerCase().indexOf('string') < 0) {
throw new Error('reverseByBuiltIn: Invalid argument ' + str);
}
return str.split(' ').reverse().join(' ')
}
console.log(reverseByBuiltIn(str)); // 'programmer a am i'
// 假设题目变了,不允许用built-in的reverse方法
// 自己实现数组的reverse方法
function reverseArr(arr) {
if (!arr || Object.prototype.toString.call(arr).toLowerCase().indexOf('array') < 0) {
throw new Error('reverseArr: Invalid argument ' + str);
}
if (arr.length === 0 || arr.length === 1) {
return arr;
} else {
return reverseArr(arr.slice(1, arr.length)).concat(arr.slice(0, 1))
}
}
function reverseStr(str) {
if (!str || Object.prototype.toString.call(str).toLowerCase().indexOf('string') < 0) {
throw new Error('reverseStr: Invalid argument ' + str);
}
if (str.length === 0 || str.length === 1) {
return str;
} else {
return reverseArr(str.split(' ')).join(' ');
}
}
console.log(reverseStr(str)); // 'programmer a am i'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment